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.
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 | 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
<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!

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 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 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.

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 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.

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'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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)
