Detect mouse hover on page load with jQuery

前端 未结 5 1532
渐次进展
渐次进展 2021-01-19 04:01

I wanted to detect whether the mouse was over an element when the web page was loaded. It appears this is not possible with jQuery - mouseover, hover etc. require a mouse mo

5条回答
  •  执笔经年
    2021-01-19 04:14

    EDIT: after testing, I have concluded this will not work. Save yourself the time and try something else.

    I think you can actually make the element bounding box work.

    This is a bit of a hack, but the strategy is to use element.offset() to get the coordinates of the element relative to the document, along with element.width() & element.height() to create a bounding box for the mouse position. You can then check an event's .pageX and .pageY values against this bounding box.

    As you correctly said, you need an event to get these coordinates, which doesn't work for you since you want them immediately. Nonetheless, have you considered faking a mouse click event by calling $('#some-element').trigger('click') after document load? You could register a function to check the bounding box via $('#some-element).click() beforehand and see what it does.

提交回复
热议问题