Home  >  Article  >  Web Front-end  >  How to get mouse position in javascript

How to get mouse position in javascript

青灯夜游
青灯夜游Original
2021-10-28 14:19:1915506browse

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;
}

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

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

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;
}

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>

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