【问题标题】:JQuery fadeOut when the mouse is not moved鼠标未移动时的JQuery淡出
【发布时间】:2016-06-05 00:30:12
【问题描述】:

我有这个 jQuery 代码,fadeInfadeOut 在它的父 div hover 上有一个子 div。如果鼠标仍然悬停在父 div 上但鼠标没有移动,我希望子 div 在五秒钟后淡出。如果它再次开始移动,子 div 会再次出现。你可以在这个简短的20sec video 中看到我的意思的一个例子:这是我到目前为止的代码:

$(document).ready(function(){
    $("#parent_div").hover(function(){
        $("#child_div").fadeIn(500);
    },
    function(){
        $("#child_div").fadeOut(500);   
    });
});

【问题讨论】:

    标签: jquery hover


    【解决方案1】:

    一种可能更好的方法是在父级上使用“mousemove”事件而不是“hover”事件。请看下面的代码:

    $(document).ready(function(){
        var childDiv = $("#child_div").hide() // start with the child hidden
          , throttle
          , fadingIn
    
        $("#parent_div").mousemove(function(event){
            clearTimeout(throttle) // clear the previous 5 second clock
    
            if (!fadingIn) { // don't runfadeIn() while the element is fading in
        	    fadingIn = true
        	    childDiv.stop(true).fadeIn(500, function () {
                    fadingIn = false
                });
            }
    
            throttle = setTimeout(function () { // create a timer to fade out child
                childDiv.fadeOut(500);
            }, 5000) // wait 5 seconds (5000 milliseconds) until it fades out the child
        });
    });
    #parent_div {
        width: 100px;
        height: 100px;
        background: #aaa;
        padding: 50px
    }
    
    #child_div {
        width: 100px;
        height: 100px;
        background: #999;
    }
      
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="parent_div">
        <div id="child_div"></div>
    </div>

    【讨论】:

    • 这很棒,现在是 2022 年(几乎),我正在使用这个 sn-p,谢谢
    【解决方案2】:

    您需要使用mousemove 事件来完成这项工作。当鼠标在元素上移动时,使用fadeIn() 并使用setTimeout() 设置计时器。在计时器中和多秒后使用fadeOut()

    var timer;
    $("#parent").mousemove(function(){
        clearInterval(timer);
        $("#child").fadeIn(500);
        timer = setTimeout(function(){
            $("#child").fadeOut(500);   
        }, 2000);  
    }).mouseleave(function(){
        $("#child").fadeOut(500);
    });
    #parent {
        width: 100px;
        height: 100px;
        border: 1px solid black;    
    }
    
    #child {
        width: 100%;
        height: 100%;
        background: green;
        display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="parent">
        <div id="child"></div>
    </div>

    【讨论】:

    • 谢谢@Mohammad ...但我更新了答案因为当我离开parent_div 时我还想要child_divfadeOut 你以前的答案必须等待timeOut即使在离开 parent_div 之后也会在淡出之前过期
    • @Mohammad,很遗憾,当我发布我的答案时,您没有正确答案(您最初使用的是“悬停”事件,它没有产生正确的结果),否则我会只是对你的投票而不是发布我自己的投票。下一次。
    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多