我想在 javascript 中创建 toast 通知。当用户完成后,消息框( toast )应该显示为绿色和文本“successfull”或其他内容。
如果没有,颜色为红色,文本应为“失败”。这个 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);
}
但我不知道的是,如何设置其余部分。放在哪里,如何从顶部中心向下滑动等等。
我知道,我可以使用
删除 divtoastDiv.remove(); // Delete the element from the DOM
但是说到“3秒后销毁它”怎么用呢?
最佳答案
由于您将 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.
});
<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>
关于Javascript - 创建和销毁 toast 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43613261/