延迟的CSS功能不起作用

时间:2011-02-11 15:06:37

标签: jquery function delay

我试图延迟CSS功能。这是我的网站: http://smartpeopletalkfast.co.uk/ppr6/press

当您将鼠标悬停在左上角图像上时,它会展开以覆盖其下方的图像。我已经使用下面的代码(它在页面头部)来改变它的z-index,因此扩展的图像总是可以看到其他任何一个:

$("document").ready(function() {   
    $(".pressimage img").mouseenter(function() {
        $(this).css('z-index','100');
            });
    $(".pressimage img").mouseleave(function() {
        $(this).css('z-index','1');
            });
});

此代码可以正常工作,但只要您将图像鼠标移开,其z-index就会发生变化,因此在将其缩小回缩略图时它不会保持可见状态。我需要的是z-index在动画完成后返回1,或者z-index变化延迟约1/2秒。我认为第二种解决方案会更简单。

我尝试使用以下内容,它确实将z-index设置为100,但从未将其恢复为1.

$("document").ready(function() {
    var timer;
    $(".pressimage img").mouseenter(function() {
        $(this).css('z-index','100');
        clearTimeout(timer);
    });
    $(".pressimage img").mouseleave(1000,function() {
         timer = setTimeout(function(){
            $(this).css('z-index','1');
         }, 500);
    });
});

谢谢

更新。我在这里发布此内容,因为您无法在评论中看到代码。这是我的实际代码和你的建议。 jq用于避免jquery版本冲突,它对我网站上的其他js工作正常。

$jq("document").ready(function() {
    $jq(".pressimage img").mouseenter(function() {

        $jq(this).stop().animate({
            width: 260
            });
    });
    $jq(".pressimage img").mouseleave(function() {
        $jq(this).stop().animate({
            width: 130
            });
    });
});


$jq("document").ready(function() {
    var timer;
    $jq(".pressimage img").mouseenter(function() {
        $jq(this).css('z-index','100');
         clearTimeout(timer);
    });
    $jq(".pressimage img").mouseleave(1000,function() {
        var that = $jq(this);
         timer = setTimeout(function(){
            that.css('z-index','1');
         },     500);
    });
});

代码现在大部分都有效,但有时会保留z-index为100的图像。 谢谢

2 个答案:

答案 0 :(得分:2)

在settimeout内部$(this)不会引用该元素。在超时函数之外引用它,并在函数内部引用引用。

http://jsfiddle.net/yK5ga/2/

第一个回答将其改为

    var that = $(this);
     timer = setTimeout(function(){
        that.css('z-index','1');
     }, 500);

我确实在昨天的js小提琴中有它,也许它被忽略了,因为我真的没有尽可能好地格式化它。

回答更新

您是否尝试将它们组合成相同的功能?

http://jsfiddle.net/yK5ga/3/

现在,你有同样的事件,做同样的元素绑定不同的事情。

更新了代码

$("document").ready(function() {
    var timer;
    $("img").mouseenter(function() {

        $(this).stop().animate({
            width: 260
        });

        $(this).css('z-index','100');
        clearTimeout(timer);
    });
    $("img").mouseleave(1000,function() {
        var that = $(this);

        $(this).stop().animate({
            width: 130
        });

         timer = setTimeout(function(){
            that.css('z-index','1');
         }, 500);
    });
})

答案 1 :(得分:0)

Ken Redler在这里回答:

Delay CSS function in Jquery?

$("document").ready(function() {
    $(".pressimage img").mouseenter(function() {
        $(this).css('z-index','1000');
            });
$(".pressimage img").mouseleave( function(){
    var that = this;
    setTimeout( function(){
      $(that).css('z-index','1');
    },500);
 });
});