jQuery使用setTimeout悬停(与hoverIntent相反)

And*_*idy 2 jquery hover settimeout hoverintent

我有一组图像,我想翻转并闪烁到不同的图像半秒左右,然后恢复到原始图像,即使鼠标仍然在图像上(即没有鼠标移出) )

建议使用setTimeout,但我无法弄清楚如何正确使用它.

http://thepool.ie/rollover/

有一个页面的例子....我只是喜欢翻转时出现的图像然后再快速消失.

我在网上搜索了一些例子,找不到任何东西......任何帮助都会非常感激.

谢谢,安德鲁

编辑:

这是我目前用于悬停图像的代码

$(document).ready(function(){   
$(function() {
    $('.rollover').hover(function() {
        var currentImg = $(this).attr('src');
        $(this).attr('src', $(this).attr('hover'));
        $(this).attr('hover', currentImg);
    }, function() {
        var currentImg = $(this).attr('src');
        $(this).attr('src', $(this).attr('hover'));
        $(this).attr('hover', currentImg);
    });
});
Run Code Online (Sandbox Code Playgroud)

});

s4y*_*s4y 7

使用setTimeout很简单.它需要一个函数作为第一个参数 - 就像许多jQuery方法一样 - 以及以毫秒为单位的时间作为第二个参数.

我从你的代码开始并重构了一下.最初,如果用户在计时器触发之前将鼠标移过,远离,然后返回图像,则可能存在竞争条件.现在,切换到备用图像并返回到原始图像的逻辑是分开的.如果图像已被换出,鼠标悬停处理程序也会短路.我还缓存了返回的jQuery对象$(this),以便稍微提高速度(缓存jQuery对象是一种很好的做法).

我将hover属性更改为data-hover(HTML5规范允许您使用自定义属性,但要求它们以它们开头data-)并在鼠标悬停选择器中检查其存在.

最后,我删除了额外的ready包装器($(document).ready(function(){…})并且$(function(){…}是相同的,不需要同时使用它们).

$(function() {
    $('.rollover[data-hover]').mouseover(function() {
        var $this = $(this), originalImage = $this.attr('src');
        if ($this.data('imagesSwapped')) {
            return;
        }
        $this.attr('src', $this.attr('data-hover')).data('imagesSwapped', true);
        setTimeout(function(){
            $this.attr('src', originalImage).removeData('imagesSwapped');
        }, 500);
    });
});
Run Code Online (Sandbox Code Playgroud)

代码尚未经过测试.