Javascript 如何使用延时翻转图像?

Javascript 如何使用延时翻转图像?,javascript,jquery,Javascript,Jquery,事实上,在产品页面中,我们希望减少服务器的负担,只在鼠标悬停2到3秒后才显示图像。因此,如果用户将光标悬停在服务器上,我们应该在2秒钟后点击服务器,并带来新的图像。但是下面的代码没有按照我们的期望工作 HTML标记: <img class="rollover-images" data-rollover="{bringNewImage()}" src="{bringOldImage()}" /> $('.rollover-images').each(function() {

事实上,在产品页面中,我们希望减少服务器的负担,只在鼠标悬停2到3秒后才显示图像。因此,如果用户将光标悬停在服务器上,我们应该在2秒钟后点击服务器,并带来新的图像。但是下面的代码没有按照我们的期望工作

HTML标记:

<img class="rollover-images" data-rollover="{bringNewImage()}" src="{bringOldImage()}" />
$('.rollover-images').each(function() {

        var newSrc = $(this).data('rollover');
        if(newSrc == 0) return;

        var timeout, oldSrc;
        $(this).hover(function() {

            timeout = setTimeout(function() {

                oldSrc = $(this).attr('src');
                $(this).attr('src', newSrc).stop(true,true).hide().fadeIn(1);

            }, 2000);

        }, function() {

            clearTimeout(timeout);
            $(this).attr('src', oldSrc).stop(true,true).hide().fadeIn(1);

        });

    });

发布的代码有几个问题

不能为HTML属性插入javascript函数,并期望它被函数返回值替换。所以你的HTML应该是

<img class="rollover-images" data-rollover="new.png" src="old.png" />

请注意,我们定义了一个名为self的新变量,该变量在setTimeout调用中使用。

发生了什么?所问问题有问题吗?为什么是-1?非常感谢!。它起作用了。HTML示例仅供参考。我们将代码作为框架的一部分进行处理。
$(this).hover(function () {
    var self = this
    timeout = setTimeout(function () {
        oldSrc = $(self).attr('src');
        $(self).attr('src', newSrc).stop(true, true).hide().fadeIn(1);
    }, 2000);
}, function () {
    clearTimeout(timeout);
    $(this).attr('src', oldSrc).stop(true, true).hide().fadeIn(1);
});