1

我正在尝试为我正在开发的网站制作一个小动画,但是按照我构建它的方式,当我将鼠标移到容器 div 上时,动画仍然会发生。我如何让它识别出鼠标实际上并没有悬停?

HTML 代码是:

<div id="badge">
    <div id="slogan">
        <p>We sell for less!</p>
    </div>
    <div id="icon"></div>
    <div id="name"></div>
    <div id="TMhold">
        <div id="TM"></div>
    </div>
</div>

这是我正在使用的 jQuery:

$("#badge").hover(
    function() {
        $(this).stop(true,true).animate({width: "250px"}, 760, "easeOutQuart");
        setTimeout(function() {
            $("#TM").stop(true,true).animate({top: "0"}, 500, "easeOutQuart");
        }, 500 );
        setTimeout(function(pee) {
            $('#badge p').stop(true,true).animate({opacity: .99}, 760, "easeOutQuart");
        }, 800 );
    },
    function() {
        clearTimeout(pee);
        $('#badge p').stop(true,true).animate({opacity: 0}, 120, "easeOutQuart");
        setTimeout(function() {
            $('#badge').stop(true,true).animate({width: "90px"}, 900, "easeOutQuart");
            $("#TM").stop(true,true).animate({ top: "-13px"}, 500, "easeOutQuart");
        }, 300 );   
    }
);

我已经阅读了 clearTimeout 函数,但我不确定这是否适用于我的解决方案。

非常感谢您的帮助或澄清!

4

1 回答 1

0

我花了一点时间重新安排 JavaScript 的布局以帮助了解实际发生的情况,我想我知道您可能遗漏了什么。该setTimeout方法返回一个值来表示正在设置的计时器。如果您不捕获此值,您将无法取消计时器。

不要调用setTimeout( function(pee)...,而是将其更改为捕获返回值,然后在clearTimeout调用中使用该值。

var hoverTimerId;

$("#badge").hover(
    function(){
        $(this).stop(true,true).animate({width: "250px"}, 760, "easeOutQuart");
        setTimeout(function() {
            $("#TM").stop(true,true).animate({top: "0"}, 500, "easeOutQuart");
        }, 500);
        hoverTimerId = setTimeout(function() {
           $('#badge p').stop(true,true).animate({ opacity: .99}, 760, "easeOutQuart");
        }, 800);
    },
    function(){
        clearTimeout(hoverTimerId);
        $('#badge p').stop(true,true).animate({opacity: 0}, 120, "easeOutQuart");

        setTimeout(function() {
            $('#badge').stop(true,true).animate({ width: "90px"}, 900, "easeOutQuart");
            $("#TM").stop(true,true).animate({top: "-13px"}, 500, "easeOutQuart");
        }, 300);
    }
);

handlerIn注意:计时器 ID 需要在回调和回调中都可用,因此我将其设置为方法调用handlerOut之外的全局变量。hover您可以在hover通话中定义它并让它仍然有效。无论哪种方式,我都没有测试过。

于 2012-03-13T17:28:02.123 回答