jQuery: How to check if the mouse is over an element

前端 未结 6 2051
庸人自扰
庸人自扰 2021-01-11 13:16

I have a deferred function that binds a mouseenter event:

$(window).load(function(e) {
  var $container = $(\'.container\');
  $container.mouseenter(function         


        
6条回答
  •  没有蜡笔的小新
    2021-01-11 13:29

    Best way to do this is to get the left, right, top, and bottom offset of the element and see if the mouse position lies anywhere between those values.

    Example.

    Put your mouse over the div the first time it loads. Then refresh the page (click F5 so you don't have to move the mouse). When the page loads fully next time, it should alert with "Hover!" even if you haven't moved your mouse.

    Or an even easier way. Just check the e.target.id of the mousemove event (which apparently fires once the page loads, even without moving the mouse) against the id of the element, like so:

    $(document).mousemove(function(e){
        if( e.target.id === 'hoverTest'){
            alert("Hovered!");
        }
    });
    

    Example (do the same steps as above).

提交回复
热议问题