Javascript定时器与不同的图像

Javascript Timer with different images

本文关键字:图像 定时器 Javascript      更新时间:2023-09-26

我有一个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的例子…实际上这里是jQuery的版本。了解正确的js更重要。

你可以把计时器设为图像,我没有图像所以我把它设为html

使用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
}

快乐编码:)

如果您想使用纯javascript,您可以给图像一个id,然后使用

访问图像
document.getElementById("imageid").src="newimage.png";

你可以像这样用jQuery改变每个属性:

var count = 0;
var speed = 1000;
countdown = setInterval(function(){
        if (count == 0) {
            return;
        }
        count--;
        $("#countdown").prop("src", count + ".png");
}
,speed);

但可能你更喜欢一个带有精灵的大图像,并将background-position样式更改为src样式,以避免新图像加载时的延迟

您可以创建一个函数,在每个间隔结束时调用它,并且在增加计数后单击它。像这样:

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。