开发者

jQuery: is mouse still over the element?

开发者 https://www.devze.com 2022-12-13 05:01 出处:网络
I would like to be able to detect if the mouse is still over the element in the following scenario: If mouseover then sleep for a few seconds.

I would like to be able to detect if the mouse is still over the element in the following scenario:

  1. If mouseover then sleep for a few seconds.
  2. Once done sleeping check of the mouse is still over the same element.
  3. If true then do something.

开发者_开发技巧How can I achieve #2?

Thank you.


This seems to work (http://jsbin.com/uvoqe)

$("#hello").hover( function () {
  $(this).data('timeout', setTimeout( function () {

    alert('You have been hovering this element for 1000ms');

  }, 1000));
}, function () {

  clearTimeout($(this).data('timeout'));

});


Take a look at the hoverIntent plugin for jQuery. It gives you a new event handler which will fire only if you have been hovering over an element for a certain amount of time. By tweaking its options, you should be able to get it to do exactly what you want.


Just use a flag to tell you if the mouse is over it.

var mouseover = false;
$('.thing').mouseenter(function(){
    mouseover = true;
}).mouseleave(function(){
    mouseover = false;
});


Here's one way:

When you set .hover() on the element, you can pass 2 functions to it. The first one will fire when the mouse is over the element, the second fires when mouse moves out.

The first function can set the currentElementId (or some other flag) and the second function will clear that. This way the only thing you need to do is to check if currentElementId is blank.


You can use setTimeout( 'sleep', sleep_time ) to call a function after a set time.

Assign event handlers to onmouseover and onmouseout.

These handlers modify a flag to check if the mouse is still on the element.

Inside of the sleep function, you can check the flag, and just return it.


I used a hyperlink to show a divand then on hover event I set the timeout property of this and as soon as I go to my div I clear the timeout and start using the div's hover function to fadeout the div. I hope this will help you.

<script type="text/javascript">
    $(document).ready(function () {
        var obj;
        $("a").hover(function () {
            if ($("#div1").is(":hidden")) {
                $("#div1").fadeIn(300).show();
            }
        }, function () {
            obj = setTimeout("jQuery('#div1').fadeOut(300);", 300);
        });

        $("#div1").hover(function () {
            clearTimeout(obj);
            if ($("#div1").is(":hidden")) {

                $("#div1").show();
            }
        }, function () {
            jQuery('#div1').fadeOut(300);
        });
    });
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消