我有一个 JS 计时器脚本,从 20 秒开始倒计时
var count = 0;
var speed = 1000;
countdown = setInterval(
function(){
jQuery("#countdown").html(count);
if (count == 0) {
return;
}
count--;
}
,speed);
有没有办法在计时器到达某个点时动态更改图像的 src?例如:
if (count >= 0 && count <= 10) {
img.src = "2.png"
}
if (count >= 11 && count <= 20) {
img.src = "1.png"
}
当用户单击按钮时,计时器的计数会增加 5:
jQuery('#add').click(function() {
if(count >= 0 && count <= 18) {count = count + 6}
因此,当值再次高于 11 时,图像 src 应恢复为 1.png
基本上它是一个根据计时器的值更改图像的 src 的脚本。
谢谢
最佳答案
在纯 JavaScript 中,你会这样做:
http://jsfiddle.net/sg3s/e54L3/
HTML:
<button>Buttan</button>
<div id="counter"></div>
Javascript:
"use strict";
(function(document) {
var counter = document.getElementById('counter'),
button = document.getElementsByTagName('button')[0],
// Added one extra to count to compensate for the one immediate countdown...
count = 6, speed = 1000, countAddStep = 5, timeout,
func = function () {
count--;
counter.innerHTML = count;
if(count !== 0) {
timeout = setTimeout(func, speed);
}
};
button.addEventListener('click', function() {
// Add the countstep to count
count = count+countAddStep;
counter.innerHTML = count;
// Restart the timeout if needed.
if (count === countAddStep) {
// Add one for the one immediate countdown
count++;
func();
}
});
// Start the timeout with 1 second (1000 ms) intervals
func();
} (document));
如果您刚刚开始学习 JavaScript,这将是一个正确的方法。如果您需要为现有的应用程序/网站实现某些功能,您可能可以使用像 jQuery 这样的库,这会稍微简化一些事情并使其更加跨浏览器兼容。
我相信人们也会发布 jQuery 示例... 实际上 here is the jQuery version 。了解正确的js更重要。
你可以将计时器设为图像,我没有图像,所以我将其保留为 html。
关于具有不同图像的 Javascript 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16163911/