当鼠标不移动时,JQuery 淡出



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

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

可能更好的方法是在父级上使用"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>

您需要使用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>

最新更新