Home >Web Front-end >JS Tutorial >Can You Determine the Mouse Position in JavaScript Without Mouse Events?

Can You Determine the Mouse Position in JavaScript Without Mouse Events?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 19:38:31897browse

Can You Determine the Mouse Position in JavaScript Without Mouse Events?

Getting Mouse Position Without Mouse Events

Can you retrieve the mouse position in JavaScript upon page load, without any mouse movement events?

Answer:

Traditionally, it's impossible to determine the mouse position without user input. However, there exists a workaround:

Tricky Approach (Avoid Using):

Create an overlaying DIV covering the entire document. Add 2,000 x 2,000 anchor elements "" within, each 1 pixel in size. Apply a CSS ":hover" rule that modifies a specific property, such as font-family.

Iterate through each of the 4 million "" elements after page load. Check the currentStyle/getComputedStyle() of each element until one changes its font. This identifies the element under the invisible cursor. Calculate the coordinates of this element to determine the mouse position.

Caution:

DO NOT USE THIS METHOD. It involves heavy DOM manipulation and performance implications. Avoid this approach for practical applications.

The above is the detailed content of Can You Determine the Mouse Position in JavaScript Without Mouse Events?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn