2

我有这个代码

var timeout = 0;
 $('#container td').each(function(){
   var td = this;
   setTimeout(function() {
     var new_text = $(td).find(text).html();
     popup_text.html(new_text);
     popup.fadeIn('fast').delay(1000).fadeOut('slow');
   }, timeout);
   timeout += 1000 + 1000;
});

我从表格单元格中获取文本并延迟显示在图层中。1个问题:如何使此代码在无限循环中运行?2问题:当你将鼠标悬停在popop循环暂时停止然后继续时,如何做到这一点?非常感谢!

4

2 回答 2

8

One way is to put the code to be repeated in a function, and have the function repeat itself at the end:

var timeout = 1000;
var action = function() {
    // Do stuff here
    setTimeout(action, timeout);
};
action();

However, as ahren suggested, setInterval might be better:

var timeout = 1000;
var action = function() {
    // Do stuff here
};
setInterval(action, timeout);

The difference is slight, but if the machine is running slowly for some reason, the setInterval version will run the code every second on average, whereas the setTimeout version will run the code once each second at most.

Neither of those methods really work well with each(), however, so you'll need to store the sequence of popups somewhere and step through them:

var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
    var td = tds[index];
    var new_text = $(td).html();
    popup.html(new_text);
    popup.fadeIn('fast').delay(1000).fadeOut('slow');

    if(++index >= tds.length)
        index = 0;        
};
setInterval(action, timeout);
action();

Finally, to avoid moving to the next popup while the popup is hovered, you can add a check for that at the start of the function. It's also necessary to rearrange the animations so that they go "check for hover - fade out - change text - fade in".

var timeout = 1000;
var tds = $('#container td');
var index = 0;
var action = function() {
    if(popup.is(':hover'))
        return;

    var td = tds[index];
    var new_text = $(td).html();
    popup.fadeOut('slow', function() {
        popup.html(new_text);
    }).fadeIn('fast');

    if(++index >= tds.length)
        index = 0;        
};
setInterval(action, timeout);
action();

jsFiddle: http://jsfiddle.net/qWkYE/2/

于 2012-08-23T23:19:35.087 回答
1

如果您喜欢简洁的方式,请使用jquery-timing 插件并编写:

$.fn.waitNoHover = function(){
  return this.is(':hover') ? this.wait('mouseleave') : this;
};
$('#popups div').repeat().each($).fadeIn('fast',$)
  .wait(200).waitNoHover().fadeOut('slow',$).all()

​</p>

请参阅http://jsfiddle.net/creativecouple/fPQdU/3/

于 2012-08-24T08:18:56.610 回答