Helllo我每隔0.5秒就会出现眨眼问题。我用#blink display =" inline"开始我的代码。但它始终保持内联。启动我的代码时,我调用startBlinking。
function startBlinking() {
setInterval(function () {
blink();
}, 1000);
}
function blink() {
setTimeout(function () {
document.getElementById('blink').style.display = "none";
}, 500);
setTimeout(function () {
document.getElementById('blink').style.display = "inline";
}, 500);
}
你能帮帮我吗?感谢。
答案 0 :(得分:4)
你的attemt的问题在于你为隐藏和显示元素设置了相同的超时长度,这意味着它将同时隐藏和显示!删除一个它应该工作:
function startBlinking() {
setInterval(function () {
blink();
}, 1000);
}
function blink() {
// note no timeout for the hiding part
document.getElementById('blink').style.display = "none";
setTimeout(function () {
document.getElementById('blink').style.display = "inline";
}, 500);
}
startBlinking();
<div id="blink">blink</div>
<p>some text following</p>
正如您所知,这会导致以下内容跳转。每当我们隐藏或显示元素时,我们也会获取元素。最好交换使用visibility
并使函数更灵活:
function blink(element, time) {
// using visibility: hidden; instead of display: none;
// allows the element to keep its rendering space
element.style.visibility = "hidden";
setTimeout(function () {
element.style.visibility = "visible";
}, time);
setTimeout(function () {
blink(element, time); // recurse
}, time * 2);
}
// query the DOM for element once instead of every iteration
blink(document.getElementById("blink"), 500);
<div id="blink">blink</div>
<p>following content stays put</p>
您可能还希望能够在某个时刻停止闪烁
function blink(element, time) {
function loop(){
element.style.visibility = "hidden";
setTimeout(function () {
element.style.visibility = "visible";
}, time);
timer = setTimeout(function () {
loop();
}, time * 2);
cleared = false;
}
var timer, cleared = true;
// expose methods
return {
start: function() {
if (cleared) loop();
},
stop: function() {
clearTimeout(timer);
cleared = true;
}
};
}
var blinking = blink(document.getElementById("blink"), 500);
document.getElementById("start").addEventListener("click", function(){
blinking.start();
});
document.getElementById("stop").addEventListener("click", function(){
blinking.stop();
});
<div id="blink">blink div</div>
<button id="start">start blinking</button><br />
<button id="stop">stop blinking</button>
答案 1 :(得分:2)
你可以通过切换类
来简化它.hide{
display:none;
}
setInterval(function () {
$('.blink').toggleClass('hide')
}, 500);
答案 2 :(得分:0)
只需调用一次,setTimeout()
将其从线程中删除,以便将其设置回inline
。
function blink() {
setTimeout(function () {
if (document.getElementById('blink').style.display === 'inline') {
document.getElementById('blink').style.display = "none";
} else {
document.getElementById('blink').style.display = "inline";
}
}, 500);
}
答案 3 :(得分:0)
你搞砸了javascript的事件队列,你为什么不试试这个
function startBlinking() {
initial = 'inline';
index = 0;
setInterval(function () {
if(index==2){
initial = (initial=='none')?'block':'none';
document.getElementById('blink').style.display = initial;
index=0;
}
index++;
}, 1000);
}
答案 4 :(得分:0)