Home Web Front-end JS Tutorial How 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;
}
Copy after login
Copy after login
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;
}
Copy after login
Copy after login

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轴坐标
}
Copy after login
Copy after login
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轴坐标
}
Copy after login
Copy after login

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>
Copy after login
Copy after login
<div id="div1">鼠标追随</div>
<script>
    var div1 = document.getElementById("div1");
    document.onmousemove = function (event) {
        pos (div1, 10, 20, event);
    }
</script>
Copy after login
Copy after login

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;
}
Copy after login
Copy after login
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;
}
Copy after login
Copy after login

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>
Copy after login
Copy after login
<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>
Copy after login
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles