【问题标题】:jQuery function not happening on hover mouseleave悬停鼠标离开时没有发生jQuery函数
【发布时间】:2012-03-13 16:55:43
【问题描述】:

我正在尝试为我正在开发的网站制作一个小动画,但是按照我构建它的方式,当我将鼠标移到容器 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 功能的信息,但我不确定这是否适用于我的解决方案。

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

【问题讨论】:

标签: jquery mouseleave jquery-hover


【解决方案1】:

我花了一点时间重新安排 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);
    }
);

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

【讨论】:

  • 太棒了!这非常有效。唯一的问题是,“TM” div 在推出后仍然存在。我也尝试为此创建另一个 var 和 clearTimeout ,但它没有用。有什么想法吗?
  • @brock2621 - 不确定那个。在我提供的代码更新中,TM 动画在一个新的超时函数中。看起来它应该在短暂的延迟后动画化。
  • 我很想知道为什么这被否决了。我错过了什么还是没有回答问题?
  • w3schools 并不是这里受人尊敬的资源。有时,哪个参考文献的答案被否决。
  • @Sparky672 - 好吧,很高兴知道。我不知道我应该避免它作为一种资源。快速的 JavaScript 语法参考非常好。您能推荐一个具有全面语法参考的更好的资源吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多