临时取消绑定鼠标输入从元素

temporary unbind mouseenter from element

本文关键字:输入 元素 鼠标 绑定 取消      更新时间:2023-09-26

我正在尝试使元素的悬停和单击事件都对相同的(在本例中为top)属性进行动画处理。

看看这个小提琴:http://jsfiddle.net/XC9Xu/1/

顶部有一个固定atop:-50pxheight=100px

1-当您悬停时,它的顶部会动画化为top=0,并且在鼠标离开顶部时再次变为top=-50

2-点击时:动画top=200px

所以问题是,你点击而不移动光标,

一切都很好,但是一旦你移动光标,它就会说:嘿,我上面的元素在哪里,我现在不在上面,回到top=-50px :D

我需要告诉它忘记过去,展望未来!

我的期望:我希望该元素在单击后保持top=300px,并且在单击后移动鼠标时不会返回到top=-50px。然后,如果您再次将光标移到它上面,它的顶部将从 300 变为 0,依此类推......

$(document).ready(function(){
    $('a')
    .hover(
        function(){
            $(this).animate({top:0});
        },
        function(){
            $(this).animate({top:-50});
        }
    )
    .on("click",function(){
        $(this).animate({top:300});
    });
});
 a{
    display:block;
    position:fixed;
    top:-50px;
    left:0;
    width:100%;
    height:100px;
    background:#ccc;
}

只需设置一个标志,并使用它来启用/禁用悬停功能。

看到这个小提琴

var click_triggered = false;
$(document).ready(function(){
    $('a')
    .hover(
        function(){
            if(!click_triggered){
                $(this).animate({top:0});
            }
        },
        function(){
            if(!click_triggered){
                $(this).animate({top:-50});
            }
        }
    )
    .on("click",function(){
        click_triggered = true;
        $(this).animate({top:300});       
    });
});

或者,如果您希望它在第二次单击后恢复,则可以执行类似此单击处理程序的操作:

    .on("click",function(){
        click_triggered = !click_triggered;
        $(this).animate({top:300});       
    });

这就可以了

$(document).ready(function(){
     reduceHeight =  function(){
            $(this).animate({top:-50});
     };
    $('a')
    .hover( function(){
            $(this).animate({top:0});
            $(this).bind('mouseleave', reduceHeight);
     })
    .click( function(){
        $(this).unbind('mouseleave');
        $(this).animate({top:300});
    });
});