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

Pure HTML+CSS to achieve typing effect

This article mainly introduces the typing effect ...

mysql solves time zone related problems

Preface: When using MySQL, you may encounter time...

Detailed process of using Vscode combined with docker for development

Preface Using Docker and VS Code can optimize the...

Explanation of building graph database neo4j in Linux environment

Neo4j (one of the Nosql) is a high-performance gr...

HTML+CSS+JavaScript to achieve list loop scrolling example code

Description: Set a timer to replace the content of...

Summary of tips for making web pages

Preface This article mainly summarizes some of th...

How to view nginx configuration file path and resource file path

View the nginx configuration file path Through ng...

Let's talk about the size and length limits of various objects in MySQL

Table of contents Identifier length limit Length ...

Three ways to communicate between Docker containers

We all know that Docker containers are isolated f...

Implement 24+ array methods in JavaScript by hand

Table of contents 1. Traversal Class 1. forEach 2...

Nine advanced methods for deduplicating JS arrays (proven and effective)

Preface The general methods are not listed here, ...

MySQL 8.0.22 download, installation and configuration method graphic tutorial

Download and install MySQL 8.0.22 for your refere...

Solution to the problem of eight hours difference in MySQL insertion time

Solve the problem of eight hours time difference ...

CSS3 animation – steps function explained

When I was looking at some CSS3 animation source ...