Javascript - 创建和销毁 toast 消息

pet*_*ann 0 html javascript css jquery

我想用 javascript 创建一个 toast 通知。当用户做得很好时,应该会出现一个消息框(toast),并显示绿色和文本“成功”或其他内容。

如果没有,颜色为红色,文本应为“失败”。这个 div 应该从屏幕中心的顶部滑动,停留 3 秒,之后,它应该从 DOM 中删除。

我在这里找到了这个,用来创建我的 div

CreateToast(isValid) { // Toast notification
        var toastDiv = document.createElement("div");
        var toastMessage;
        var foreColor;
        var backgroundColor;
        var borderColor;

        if (!isValid) {
            toastMessage = "Failure";
            foreColor = "";
            backgroundColor = "";
            borderColor = "";
        } else {
            toastMessage = "Success";
            foreColor = "";
            backgroundColor = "";
            borderColor = "";
        }

        toastDiv.innerHTML = toastMessage;
        document.body.appendChild(toastDiv);
    }
Run Code Online (Sandbox Code Playgroud)

但我不知道如何设置其余部分。将其放置在哪里,如何从顶部中心滑落等。

我知道,我可以使用删除 div

toastDiv.remove(); // Delete the element from the DOM
Run Code Online (Sandbox Code Playgroud)

但是“3秒后销毁”怎么用呢?

Lou*_*tte 6

由于您将 jQuery 标记为您的问题,我假设您想使用一些 jQuery 方法。

所以这是基本的例子:(我相信你将能够按照你的意愿设计它的样式)
对于每个创建的 div,你必须分配一个唯一的id,以便能够创建它slideDown()并为其分配一个唯一的.remove()

所以我添加了一个toastCounter来创建这个id

var toastCounter=0;

function CreateToast(isValid) { // Toast notification
  
  var toastDiv = document.createElement("div");
  
  // Give it a unique id
  toastDiv.id = "toast_"+toastCounter;
  
  // Make it hidden (necessary to slideDown)
  toastDiv.style.display = "none";
  
  var toastMessage;
  var foreColor;
  var backgroundColor;
  var borderColor;

  if (!isValid) {
    toastMessage = "Failure";
    foreColor = "";
    backgroundColor = "";
    borderColor = "";
  } else {
    toastMessage = "Success";
    foreColor = "";
    backgroundColor = "";
    borderColor = "";
  }

  toastDiv.innerHTML = toastMessage;
  document.body.appendChild(toastDiv);
  
  // Increment toastCounter
  toastCounter++;
}



$("#test1").on("click",function(){
  CreateToast(true);
  var thisToast = toastCounter-1;
  
  // Make it slide down
  $(document).find("#toast_"+thisToast).slideDown(600);
  
  setTimeout(function(){
    $(document).find("#toast_"+thisToast).slideUp(600,function(){   // Slideup callback executes AFTER the slideup effect.
      $(this).remove();
    });
  },3000);  // 3sec.
});

$("#test2").on("click",function(){
  CreateToast(false);
  var thisToast = toastCounter-1;
  
  // Make it slide down
  $(document).find("#toast_"+thisToast).slideDown(600);
  
  setTimeout(function(){
    $(document).find("#toast_"+thisToast).slideUp(600,function(){   // Slideup callback executes AFTER the slideup effect.
      $(this).remove();
    });
  },3000);  // 3sec.
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="test1">TRUE</button>
<button id="test2">FALSE</button>
Run Code Online (Sandbox Code Playgroud)