1

jQuery 1.4.2:

我有一个图像。当 mouseover 事件被触发时,会执行一个函数,该函数运行一个循环来加载多个图像。相反, mouseout 事件需要将图像设置回预定图像,并且不再执行循环。这些仅适用于“拇指”类的图像:

$("img.thumb").live("mouseover mouseout", function(event) {
    //var foo = $(this).attr('id');
    var wait;
    var i=0;
    var image = document.getElementById(foo);

    if (event.type == 'mouseover') {
        function incrementimage()
        {
            i++;
            image.src = 'http://example.com/images/file_'+i+'.jpg';
            if(i==30) {i=0;}
        }    
        wait = setInterval(incrementimage,500);
    } else if (event.type == 'mouseout') {
        clearInterval (wait);
        image.src = 'http://example.com/images/default.jpg';
    }
    return false;
});

当我鼠标移出时,图像设置为 default.jpg 但浏览器继续循环浏览图像。它永远不会停止。有人可以用一些知识打我吗?谢谢。

4

3 回答 3

2

您可以将代码缩短为此以正确清除间隔:

$("img.thumb").live("mouseover", function() {
  var i = 0, image = this, incrementimage = function() {
    i++;
    image.src = 'http://example.com/images/file_'+i+'.jpg';
    if(i==30) {i=0;}
  };
  $(this).data('timer', setInterval(incrementimage,500));
}).live("mouseout", function() {
  clearInterval($(this).data('timer'));
  this.src = 'http://example.com/images/default.jpg';
});

这将.live()调用拆分以使逻辑更清晰,并使用而不是作为全局变量将先前的waitid 存储在元素本身上。.data()

于 2010-05-10T02:18:12.793 回答
1

问题是 mouseout 事件与waitmouseover 事件不同。您需要将其存储在其他地方。我建议使用 [data()][1]将其存储在元素上。

此外,这个序列没有意义:

var foo = $(this).attr('id');
...
var image = document.getElementById(foo);

this已经是图像元素。

最后,这不是我定义函数的方式。尝试类似:

$("img.thumb").live("mouseover", function(evt) {
  var wait = $(this).data("wait");
  if (!wait) {
    clearInterval(wait);
  }
  var i = 0;
  var image = this;
  var incrementImage = function() {
    i++;
    image.src = "http://example.com/images/file_" + i + ".jpg";
    if (i == 30) {
      i = 0;
    }
  }
  wait = setInterval(incrementImage, 500);
  $(this).data("wait", wait);
  return false;
});

$("img.thumb").live("mouseout", function(event) {
  var wait = $(this).data("wait");
  if (wait) {
    clearInterval(wait);
  }
  img.src = "http://example.com/default.jpg";
  return false;
});
于 2010-05-10T02:08:24.547 回答
0

您是否尝试过将您var wait的 .live() 事件移到外面?

var wait
$("img.thumb").live("mouseover mouseout", function(event) {
于 2010-05-10T02:08:59.350 回答