If mouse over for over 2 seconds then show else do

2019-01-31 03:16发布

Here is a jQuery slide function I have applied to a div on hover in order to slide a button down.

It works fine except that now everytime someone moves in and out of it, it keeps bobbing up and down.

I figured if I put a one or two second delay timer on it it would make more sense.

How would I modify the function to run the slide down only if the user is on the div for over a second or two?

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>
<script type="text/javascript">

$("#NewsStrip").hover(
function () {
    $("#SeeAllEvents").slideDown('slow');    },
function () {
    $("#SeeAllEvents").slideUp('slow');
});

</script>

2条回答
萌系小妹纸
2楼-- · 2019-01-31 03:44

You need to set a timer on mouseover and clear it either when the slide is activated or on mouseout, whichever occurs first:

var timeoutId;
$("#NewsStrip").hover(function() {
    if (!timeoutId) {
        timeoutId = window.setTimeout(function() {
            timeoutId = null; // EDIT: added this line
            $("#SeeAllEvents").slideDown('slow');
       }, 2000);
    }
},
function () {
    if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
    }
    else {
       $("#SeeAllEvents").slideUp('slow');
    }
});

See it in action.

查看更多
forever°为你锁心
3楼-- · 2019-01-31 04:01
var time_id;

$("#NewsStrip").hover(
function () {
    if (time_id) {
        clearTimeout(time_id);
    } 
    time_id = setTimeout(function () {
        $("#SeeAllEvents").stop(true, true).slideDown('slow');
    }, 2000);
}, function () {
    if (time_id) {
        clearTimeout(time_id);
    } 
    time_id = setTimeout(function () {
        $("#SeeAllEvents").stop(true, true).slideUp('slow');
    }, 2000);
});
查看更多
登录 后发表回答