我有一个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
基本上它是一个脚本,它根据timer的值改变图像的src。
由于
答案 0 :(得分:2)
在纯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。
答案 1 :(得分:0)
使用Jquery可以轻松更改图像的src。
var newSrc="..... " ; // new img path
$('#img1').attr('src',newSrc ); //changing the image
编辑:
jQuery('#add').click(function() {
if(count >= 0 && count <= 18)
{
if(count==11)
{
var newSrc="..... " ; // new img path
$('#img1').attr('src',newSrc ); //changing the image
}
count = count + 6
}
快乐编码:)
答案 2 :(得分:0)
如果你想使用普通的javascript,你可以给图像一个id,然后使用
访问图像document.getElementById("imageid").src="newimage.png";
并将其更新为所需的图像。
答案 3 :(得分:0)
您可以使用jQuery更改每个属性:
var count = 0;
var speed = 1000;
countdown = setInterval(function(){
if (count == 0) {
return;
}
count--;
$("#countdown").prop("src", count + ".png");
}
,speed);
但是,您可能更喜欢使用精灵制作一张大图片并更改background-position
样式而不是src
,以避免在加载新图片时出现延迟。
答案 4 :(得分:0)
您可以创建一个在每个间隔结束时调用的函数,也可以在递增计数后单击。 像这样:
function validateImg(){
var $img = $('#imgID');
if (count >= 0 && count <= 10 && $img.attr('src') !='2.png') {
$img.attr('src','2.png');
}
if (count >= 11 && count <= 20 && $img.attr('src') !='1.png') {
$img.attr('src','1.png');
}
}
这样,只有当计数在正确的时间间隔内时才会改变img