如何让这个Jquery闪烁的背景在几秒后停止?我正在尝试将背景和文本设置为闪烁,然后在3秒后停止。感谢您的帮助!
$(document).ready(function() {
blinkFont();
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
setTimeout("setblinkFont()", 500)
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
setTimeout("blinkFont()", 500)
}
#blink {
text-align: center;
background: #000000;
color: #F00;
margin: 0;
padding: 20px;
}
#blink span {
font-size: 2em;
font-weight: bold;
display: block;
}
<div id="blink"><span>This is blinking text and background</span>
</div>
答案 0 :(得分:0)
使用SetInterval代替SetTimeout,保留变量。并保留一个计数器,一旦达到所需的重复次数,停止间隔,计数器将在每次执行后递增。 像这样:
myVar=setInterval("javascript function", milliseconds);
//check your counter value.
window.clearInterval(myVar)
答案 1 :(得分:0)
虽然我可以想到一些更优雅的方法来实现这一点,但不会更改太多的当前结构,您可以将超时存储在变量中,然后使用clearInterval,这会停止一个计时器,在三秒钟后停止复发:
<script>
var intervalA;
var intervalB;
$(document).ready(function() {
blinkFont();
setTimeout(function() {
clearInterval(intervalA); clearInterval(intervalB);},3000);
});
function blinkFont() {
document.getElementById("blink").style.color = "red"
document.getElementById("blink").style.background = "black"
intervalA = setTimeout("setblinkFont()", 500);
}
function setblinkFont() {
document.getElementById("blink").style.color = "black"
document.getElementById("blink").style.background = "red"
intervalB = setTimeout("blinkFont()", 500);
}
</script>
</head>
<body>
<div id="blink"><span>This is blinking text and background</span>
</div>
</body>
答案 2 :(得分:0)
这fiddle对你满意吗?
代码:
$(document).ready(function() {
var intval;
intval = setInterval(function(){
blinkFont();
},500);
setTimeout(function() {
alert('clear');
clearInterval(intval);
}, 3000);
});
function blinkFont() {
var curColor = document.getElementById("blink").style.color;
var curBgC = document.getElementById("blink").style.background;
document.getElementById("blink").style.color = curColor === "red" ? "blue" : "red";
document.getElementById("blink").style.background = curBgC === "black" ? "yellow" : "black";
}
答案 3 :(得分:0)
您必须使用SetTimeout(),SetInterval()和clearInterval(),如下所示。
<强> Click Here to see working Demo 强>
<强> HTML 强>
<div id="blink"><span>Demo</span>
</div>
<强> Jquery的强>
$(document).ready(function(){
var myVar;
myVar = setInterval(blinkFont, 500);
function blinkFont() {
var curColor = document.getElementById("blink").style.color;
var curBgC = document.getElementById("blink").style.background;
document.getElementById("blink").style.color = curColor === "red" ? "blue" : "red";
document.getElementById("blink").style.background = curBgC === "black" ? "yellow" : "black";
}
setTimeout(function () {
$("#blink").css('visibility', 'visible');
clearInterval(myVar);
}, 3000); // after 3 seconds it'll stop blinking
});