在jQuery中创建一个更改图像的间隔? [英] Create an interval to change image in jQuery?

查看:97
本文介绍了在jQuery中创建一个更改图像的间隔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a working script like this:

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,依此类推。

Yeah, you guessed right. It's made to change YouTube's thumbnail on interval. However, I have no idea, how to create the interval. It now changes the thumbnail to 1.jpg, which is another thumbnail, but it should next change the image to 2.jpg in 1 second and so on.

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

The whole snippet should probably be written from scratch. Advice?

希望你理解:-D

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

I changed the variable-names from finnish words, I don't use them. Just in this example.

Martti Laine

Martti Laine

推荐答案

新的默认保留字。你不能使用它们。

new and default are reserved words in javascript. You cannot use them.

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

To create an interval you should use setInterval:

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






[< a href =http://jsbin.com/ekeku4/5/ =nofollow noreferrer>看到它在行动]




[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中创建一个更改图像的间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆