jquery - 在 jQuery 中创建一个更改图像的间隔?

标签 jquery image timer rotation src

我有一个像这样的工作脚本:

jQuery(document).ready(function(){

    $('.video-thumb img').bind('mouseover',function(){
        var new = $(this).attr('src').replace(/default.jpg/,'1.jpg');
        $(this).attr('src',new);
    }).bind('mouseout',function(){
        var default = $(this).attr('src').replace(/[0-9].jpg/,'default.jpg');
        $(this).attr('src',default);
    });

});

是的,你猜对了。它是为了定期更改 YouTube 的缩略图而设计的。但是,我不知道如何创建间隔。现在,它会将缩略图更改为 1.jpg,这是另一个缩略图,但接下来应该会在 1 秒内将图像更改为 2.jpg,依此类推。

整个片段可能应该从头开始编写。建议?

希望你理解:-D

编辑:我更改了芬兰语单词的变量名称,我不使用它们。就在这个例子中。

马蒂·莱恩

最佳答案

默认reserved words在 JavaScript 中。你不能使用它们。

要创建间隔,您应该使用setInterval:

setInterval(function() {
  // do something
  // ...
}, 1000); // <- 1000ms = 1s
<小时/>

[See it in action ]

jQuery(document).ready(function() {

    var timer, imgsrc, cnt = 0;

    $('.video-thumb img').bind('mouseover', function() {

      // if there is no timer
      if (!timer) {

        var $t = $(this);

        // get the image src
        imgsrc = $t.attr('src').replace('default.jpg','');

        // start a new timer
        timer = setInterval(function() {

          // periodically change the src
          $t.attr('src', imgsrc + (cnt+1) + ".jpg");

          // and adjust the counter
          cnt = ( cnt + 1 ) % 3; // 0, 1, 2

        }, 1000); // <- 1000ms = 1s
      }
    }).bind('mouseout',function() {

      // stop rotation
      if (timer) {
        clearInterval(timer);
        timer = null;
      }

      // set the default img
      $(this).attr('src', imgsrc + 'default.jpg');
    });
});

关于jquery - 在 jQuery 中创建一个更改图像的间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3181861/

相关文章:

javascript - 使用唯一 id 动态附加 html 并使用 Jquery 删除正确的 html

timer - Swift:测试 NSTimer 的过期/失效似乎失败

javascript - 错误 : timers. js :234 callback. 应用(计时器,参数);

java - 计时器 t = 新计时器(50,b); t.停止();不管用

iOS Swift 在 WebView 中显示 Xcassets 图像

css - 使 2 个背景图像相等

javascript - 当鼠标在不同的 div 上时更改一个 div 的背景图像

JQuery - .position 不返回相对于父级的偏移量

javascript - 下拉选择表单,转到提交时的 URL

c++ - 使用 Magick++ 解码 PNG 图像