我正在使用一个div,就像完成的味精一样。它应该在过程完成时出现,并在几秒钟后消失。为此,我编写了以下代码片段:
console.log("Hi from a module");
function showProcessFinishedMsg(msg) {
var done_msg = document.getElementById("done_msg");
var done_msg_text = document.getElementById("done_msg_text");
done_msg_text.innerHTML = msg;
unfade(done_msg);
setTimeout(fade(done_msg),60000);
}
//fading in
function unfade(element) {
var op = 0.1; // initial opacity
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
//fading out
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
.done_msg {
height: 50px;
width: 80%;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
bottom: 20px;
background-color: #212121;
border-radius: 8px;
box-shadow: 1px 1px 5px #0d0d0d;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
}
.done_msg_text {
padding-left: 30px;
color: #ffffff;
}
但是正如您所看到的,我有问题,那就是运行不顺利。而且它如此怪异地闪烁。希望任何人都能帮助我。
〜filip
答案 0 :(得分:1)
您的问题在于:
setTimeout(fade(done_msg), 60000);
在这里,您在执行此行时正在调用fade
函数,而不是您想的那样每一分钟。
setTimeout
的第一个参数应该是可以执行的函数,但是,您正在立即执行该函数,因此将第一个参数设置为{{ 1}},即fade
。
这将导致您的undefined
和unfade
函数同时运行,从而导致闪烁。而是将fade
包装在其自己的函数中:
fade(done_msg)
请参见下面的工作示例:
setTimeout(_ => fade(done_msg), 60000);
function showProcessFinishedMsg(msg) {
var done_msg = document.getElementById("done_msg");
var done_msg_text = document.getElementById("done_msg_text");
done_msg_text.innerHTML = msg;
unfade(done_msg);
setTimeout(_ => fade(done_msg), 2000);
}
//fading in
function unfade(element) {
var op = 0.1; // initial opacity
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
element.style.display = 'flex';
var timer = setInterval(function() {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
//fading out
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function() {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
.done_msg {
height: 50px;
width: 80%;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
bottom: 20px;
background-color: #212121;
border-radius: 8px;
box-shadow: 1px 1px 5px #0d0d0d;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
}
.done_msg_text {
padding-left: 30px;
color: #ffffff;
}