Teach you how to get the pointer position in javascript

Teach you how to get the pointer position in javascript

The method of obtaining the position of the pointer in javascript is: using the pageX and pageY, or clientX and clientY properties of the event object, and cooperating with the scrollLeft and scrollTop properties, so that the position of the pointer can be calculated.

The operating environment of this article: Windows 10 system, JavaScript 1.8.5, ThinkPad T480 computer.

To get the position of the pointer on the page, you can use the pageX and pageY, or clientX and clientY (IE compatible) properties of the event object, and also need to cooperate with the scrollLeft and scrollTop properties, so that you can calculate the position of the mouse pointer on the page.

//Get the page position of the mouse pointer //Parameter: e represents the current event object //Return value: Returns the coordinates of the mouse relative to the page, object format (x, y)

function getMP(e) {

    var e = e || window.event;

    return {

        x : e.pageX || e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft),

        y : e.pageY || e.clientY + (document.documentElement.scrollTop || document.body.scrollTop)

    }

}

The pageX and pageY event attributes are not supported by IE browsers, and the clientX and clientY event attributes are not supported by Safari browsers, so you can mix them to be compatible with different browsers. For quirks mode, the body element represents the page area, and the html element is hidden, but in standard mode, the html element represents the page area, and the body element is only an independent page element, so these two parsing methods need to be compatible.

The following example demonstrates how to call the above extended function getMP() to capture the current position of the mouse pointer in the document.

<body style="width:2000px;height:2000px;">
    <textarea id="t" cols="15" rows="4" style="position:fixed;left:50px;top:50px;"></textarea>
</body>
<script>
    var t = document.getElementById("t");
    document.onmousemove = function(e){
        var m = getMP(e);
        t.value = "mouseX = " + mx + "\n" + "mouseY = " + my
    }
</script>

The demonstration effect is as follows:

Get the relative position of the pointer

Use offsetX and offsetY or layerX and layerY to get the offset position of the mouse pointer relative to the containing box. If you use the offsetLeft and offsetTop properties to get the offset coordinates of the element in the positioning containing box, and then use the layerx property value to subtract the offsetLeft property value, and use the layery property value to subtract the offsetTop property value, you can get the position of the mouse pointer inside the element.

//Get the position of the mouse pointer within the element //Parameters: e represents the current event object, o represents the current element //Return value: Returns the relative coordinate object function getME (e, o) {

    var e = e || window.event;

    return {

        x : e.offsetX || (e.layerX - o.offsetLeft),

        y : e.offsetY || (e.layerY - o.offsetTop)

    }

}

In practice, the above function has the following two problems:

  • Mozilla Type and Safari use the upper left corner of the element's border outer wall as the reference point.
  • Other browsers use the upper left corner of the inner wall of the element's border as the coordinate origin.

Considering the influence of border on mouse position, when the border of an element is very wide, we must consider how to eliminate the influence of border on mouse position. However, due to different border styles, it has a default width of 3 pixels, which brings trouble to obtaining the actual width of the element's border. More conditions need to be set to determine the border width of the current element.

Example

The improved extended function for getting the position of the mouse pointer within an element is as follows:

//Perfectly obtain the position of the mouse pointer within the element //Parameters: e represents the current event object, o represents the current element //Return value: Returns the coordinate position of the mouse relative to the element, where x represents the x-axis offset distance and y represents the y-axis offset distance function getME(e, o){

    var e = e || window.event;

    //Get the width of the left border of the element //Call the getStyle() extension function to get the border style value and try to convert it to a numerical value. If the conversion is successful, assign the value.

    //Otherwise, determine whether the border style is defined. If the border style is defined and the value is not none, it means that the border width is the default value, which is 3 pixels.

    //If no border style is defined and the width value is auto, the border width is 0

    var bl = parseInt(getStyle(o, "borderLeftWidth")) || ((o.style.borderLeftStyle && o.style.borderLeftStyle != "none" )? 3 : 0);

    //Get the width of the top border of the element. The design idea is the same as that of getting the left border. var bt = parseInt(getStyle(o, "borderTopWidth")) || ((o.style.borderTopStyle && o.style.borderTopStyle !="none" ) ? 3 : 0);

    var x = e.offsetX || (e.layerX - o.offsetLeft - bl); // Mouse offset value for general browsers // Compatible with Mozilla browsers, minus border width var y = e.offsetY || (e.layerY - o.offsetTop - bt); // Mouse offset value for general browsers // Compatible with Mozilla browsers, minus border width var u = navigator.userAgent; // Get browser user data if( (u.indexOf("KHTML") > - 1) ||(u.indexOf("Konqueror") > - 1) || (u.indexOf("AppleWebKit") > - 1)

    ){ // If it is Safari browser, subtract the border effect x -= bl; y -= bt;

    } return { // Returns a mouse position object compatible with different browsers, with the upper left corner of the inner wall of the element border as the positioning origin x: x, y: y

    }  

}

The demonstration effect is as follows:

Recommended learning: JavaScript video tutorial

This is the end of this article about how to get the pointer position in javascript. For more information about the location of js pointer, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Examples of variables, pointers, and reference functions and operations in JavaScript
  • A brief discussion on pointers and addresses in JavaScript
  • Sharing a new understanding of the this pointer in JavaScript
  • Discussion on js variable scope and this pointer
  • Three ways to change the this pointer inside a javascript function
  • Javascript this pointer

<<:  W3C Tutorial (10): W3C XQuery Activities

>>:  Ubuntu Server 18.04.5 LTS Server Edition Installation and Configuration Graphic Tutorial

Recommend

Mini Program implements custom multi-level single-select and multiple-select

This article shares the specific code for impleme...

How to use Maxwell to synchronize MySQL data in real time

Table of contents About Maxwell Configuration and...

Detailed explanation of slave_exec_mode parameter in MySQL

Today I accidentally saw the parameter slave_exec...

Personal opinion: Talk about design

<br />Choose the most practical one to talk ...

Two simple ways to remove text watermarks from web pages

<br /> When we browse certain websites and s...

A brief discussion on the role of Vue3 defineComponent

Table of contents defineComponent overload functi...

How to view the IP address of Linux in VMware virtual machine

1. First, double-click the vmware icon on the com...

How to configure pseudo-static and client-adaptive Nginx

The backend uses the thinkphp3.2.3 framework. If ...

How to set a fixed IP address for a VMware virtual machine (graphic tutorial)

1. Select Edit → Virtual Network Editor in the me...

Detailed steps to install Mysql5.7.19 using yum on Centos7

There is no mysql by default in the yum source of...

Script example for starting and stopping spring boot projects in Linux

There are three ways to start a springboot projec...