search
HomeWeb Front-endJS TutorialHow to get mouse position in javascript

How to get mouse position in javascript

Oct 28, 2021 pm 02:19 PM
javascript

JS method to obtain mouse position: 1. Use clientX and clientY attributes; 2. Use offsetX and offsetY attributes; 3. Use pageX and pageY attributes; 4. Use screenX and screenY attributes; 5. Use layerX and layerY attribute.

How to get mouse position in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, when an event occurs, getting the position of the mouse is a very important event. Due to browser incompatibility, different browsers define different attributes in their respective event objects, as shown in the following table. These attributes define the coordinates of the mouse pointer in pixel values, but because they refer to different coordinate systems, it is troublesome to accurately calculate the position of the mouse.

Properties and their compatibility
Properties Description Compatibility
clientX Take the upper left corner of the browser window as the origin and position the x-axis coordinate All browsers, not compatible with Safari
clientY Taking the upper left corner of the browser window as the origin, position the y-axis coordinate All browsers, not compatible with Safari
offsetX Take the upper left corner of the target object of the current event as the origin and position the x-axis coordinate All browsers, not compatible with Mozilla
offsetY Take the upper left corner of the target object of the current event as the origin and position the y-axis coordinate All browsers, not compatible with Mozilla
pageX Take the upper left corner of the document object (i.e. document window) as the origin and position the x-axis coordinate All browsers, not compatible with IE
pageY Use the upper left corner of the document object (i.e. document window) as the origin and position the y-axis coordinate All browsers, not compatible with IE
screenX The upper left corner of the computer screen is the origin, and the x-axis coordinate is positioned All browsers
screenY The upper left corner of the computer screen is the origin, Positioning y-axis coordinate All browsers
layerX The nearest absolutely positioned parent element (if not, the document object) top left Corner is the element, positioned at the x-axis coordinate Mozilla and Safari
layerY The nearest absolutely positioned parent element (or document if none Object) is the upper left corner of the element, positioning the y-axis coordinate Mozilla and Safari

Example 1

The following describes how to use multiple mouse coordinate attributes to achieve a mouse positioning design that is compatible with different browsers.

First, let’s take a look at the screenX and screenY properties. These two attributes are supported by all browsers and should be said to be the most preferred attributes, but their coordinate system is the computer screen, that is, the upper left corner of the computer screen is the origin of positioning. This has no value for web pages that use the browser window as their active space. Because different screen resolutions, different browser window sizes and positions make it difficult to position the mouse on a web page.

Secondly, if the document object is used as the coordinate system, you can consider using the pageX and pageY attributes to achieve positioning in the browser window. This is a good idea for designing mouse following, because the following element generally moves in the browser window in an absolutely positioned manner. In the mousemove event handler, pass the pageX and pageY attribute values ​​​​to the top and left of the absolutely positioned element. Just style attributes.

The IE event model does not support the above attributes, so we need to find a method that is compatible with IE. The clientX and clientY attributes are based on the window object as the coordinate system, and the IE event model supports them, so you can choose them. However, considering the possible scroll bar offset of objects such as window, the offset of the page scroll relative to the window object should also be added.

var posX = 0, posY = 0;
var event = event || window.event;
if (event.pageX || event.pageY) {
    posX = event.pageX;
    posY = event.pageY;
} else if (event.clientX || event.clientY) {
    posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
    posY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
}
var posX = 0, posY = 0;
var event = event || window.event;
if (event.pageX || event.pageY) {
    posX = event.pageX;
    posY = event.pageY;
} else if (event.clientX || event.clientY) {
    posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
    posY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
}

In the above code, first check whether the pageX and pageY attributes exist, and if they exist, get their values; if not If exists, detect and obtain the clientX and clientY attribute values, and then add the scrollLeft and scrollTop attribute values ​​of the document.documentElement and document.body objects, so that the same coordinate values ​​are obtained in different browsers.

Example 2

Encapsulate mouse positioning code. Design idea: According to the specific object passed and the offset relative to the mouse pointer, the object can be commanded to follow the water conservation movement.

First define an encapsulation function. The parameters passed in by the design function are the object reference pointer, the offset distance relative to the mouse pointer, and the event object. Then the encapsulated function can obtain the coordinate value of the mouse based on the event object, and set the object to absolute positioning. The absolute positioning value is the current coordinate value of the mouse pointer.

The encapsulation code is as follows:

var pos = function (o, x, y, event) {  //鼠标定位赋值函数
    var posX = 0, posY = 0;  //临时变量值
    var e = event || window.event;  //标准化事件对象
    if (e.pageX || e.pageY) {  //获取鼠标指针的当前坐标值
        posX = e.pageX;
        posY = e.pageY;
    } else if (e.clientX || e.clientY) {
        posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        posY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }
    o.style.position = "absolute";  //定义当前对象为绝对定位
    o.style.top = (posY + y) + "px";  //用鼠标指针的y轴坐标和传入偏移值设置对象y轴坐标
    o.style.left = (posX + x) + "px";  //用鼠标指针的x轴坐标和传入偏移值设置对象x轴坐标
}
var pos = function (o, x, y, event) {  //鼠标定位赋值函数
    var posX = 0, posY = 0;  //临时变量值
    var e = event || window.event;  //标准化事件对象
    if (e.pageX || e.pageY) {  //获取鼠标指针的当前坐标值
        posX = e.pageX;
        posY = e.pageY;
    } else if (e.clientX || e.clientY) {
        posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        posY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }
    o.style.position = "absolute";  //定义当前对象为绝对定位
    o.style.top = (posY + y) + "px";  //用鼠标指针的y轴坐标和传入偏移值设置对象y轴坐标
    o.style.left = (posX + x) + "px";  //用鼠标指针的x轴坐标和传入偏移值设置对象x轴坐标
}

The encapsulation code is tested below. Register the mouse movement event handler for the document object, and pass in the mouse positioning encapsulation function. The object passed in is the

element, and its position is offset by (10,20) to the lower right of the mouse pointer. Considering that the DOM event model passes event objects in the form of parameters, don't forget to pass the event object in the calling function.
<div id="div1">鼠标追随</div>
<script>
    var div1 = document.getElementById("div1");
    document.onmousemove = function (event) {
        pos (div1, 10, 20, event);
    }
</script>
<div id="div1">鼠标追随</div>
<script>
    var div1 = document.getElementById("div1");
    document.onmousemove = function (event) {
        pos (div1, 10, 20, event);
    }
</script>

Example 3

Get the coordinates of the mouse pointer within the element. This can be achieved using the offsetX and offsetY properties, but is not supported by the Mozilla browser. The layerX and layerY attributes can be optionally used to be compatible with the Mozilla browser.

The design code is as follows:

var event = event || window.event;
if (event.offsetX || event.offsetY) {  //适用非Mozilla浏览器
    x = event.offsetX;
    y = event.offsetY;
} else if (event.layerX || event.layerY) {  //兼容Mozilla浏览器
    x = event.layerX;
    y = event.layerY;
}
var event = event || window.event;
if (event.offsetX || event.offsetY) {  //适用非Mozilla浏览器
    x = event.offsetX;
    y = event.offsetY;
} else if (event.layerX || event.layerY) {  //兼容Mozilla浏览器
    x = event.layerX;
    y = event.layerY;
}

However, the layerX and layerY attributes are based on the absolutely positioned parent element. The reference object, rather than the element itself. If there is no absolutely positioned parent element, the document object will be used as the reference. To this end, you can add it dynamically through scripts or add it manually, and design an absolutely positioned parent element surrounding the outer layer of the element, which can solve browser compatibility issues. To account for the error caused by the distance between elements, it is appropriate to subtract an offset of 1 or a few pixels.

The complete design code is as follows:

<input type="text" id="text" />
<span style="position:absolute;">
    <div id="div1" style="width:200px;height:160px;border:solid 1px red;">鼠标跟随</div>
</span>
<script>
    var t = document.getElementById("text");
    var div1 = document.getElementById("div1");
    div1.onmousemove = function (event) {
        var event = event || window.event;  //标准化事件对象
        if (event.offsetX || event.offsetY) {
            t.value = event.offsetX + "" + event.offsetY;
        } else if (event.layerX || event.layerY) {
            t.value = (event.layerX-1) + "" + (event.layerY-1);
        }
    }
</script>
<input type="text" id="text" />
<span style="position:absolute;">
    <div id="div1" style="width:200px;height:160px;border:solid 1px red;">鼠标跟随</div>
</span>
<script>
    var t = document.getElementById("text");
    var div1 = document.getElementById("div1");
    div1.onmousemove = function (event) {
        var event = event || window.event;  //标准化事件对象
        if (event.offsetX || event.offsetY) {
            t.value = event.offsetX + "" + event.offsetY;
        } else if (event.layerX || event.layerY) {
            t.value = (event.layerX-1) + "" + (event.layerY-1);
        }
    }
</script>

This approach can solve the problem of positioning the mouse pointer inside the element . However, because an absolutely positioned element is wrapped around the element, it will destroy the structural layout of the entire page. This method can be considered on the premise of ensuring that this artificial approach will not cause confusion in the structural layout.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to get mouse position in javascript. 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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)