Home Web Front-end JS Tutorial How to get the position of the pointer in javascript

How to get the position of the pointer in javascript

Oct 25, 2021 pm 02:47 PM
javascript Location pointer

Javascript method to get the position of the pointer: use the pageX and pageY, or clientX and clientY attributes of the event object, and cooperate with the scrollLeft and scrollTop attributes, so that the position of the pointer can be calculated.

How to get the position of the pointer in javascript

#The operating environment of this article: windows10 system, javascript 1.8.5, thinkpad t480 computer.

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

//获取鼠标指针的页面位置
//参数:e表示当前事件对象
//返回值:返回鼠标相对页面的坐标,对象格式(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)
    }
}
Copy after login

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

The following example demonstrates how to call the above extension function getMP() to capture the current mouse pointer position 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 = " + m.x  + "\n" + "mouseY = " + m.y
    }
</script>
Copy after login

The demonstration effect is as follows:

How to get the position of the pointer in javascript

Get the relative position of the pointer

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

//获取鼠标指针在元素内的位置
//参数:e表示当前事件对象,o表示当前元素
//返回值:返回相对坐标对象
function getME (e, o) {
    var e = e || window.event;
    return {
        x : e.offsetX || (e.layerX - o.offsetLeft),
        y : e.offsetY || (e.layerY - o.offsetTop)
    }
}
Copy after login

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

  • Mozilla type and Safari browser use the upper left corner of the outer wall of the element border as the reference point.

  • Other browsers use the upper left corner of the inner wall of the element border as the coordinate origin.

Considering the impact of the border on the mouse position, when the element border is very wide, you must consider how to eliminate the impact of the border on the mouse position. However, due to the different border styles, it has a default width of 3 pixels, which makes it troublesome to get 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 extension function to obtain the position of the mouse pointer within the element is as follows:

//完善获取鼠标指针在元素内的位置
//参数:e表示当前事件对象,o表示当前元素
//返回值:返回鼠标相对元素的坐标位置,其中x表示x轴偏移距离,y表示y轴偏移距离
function getME(e, o){
    var e = e || window.event;
    //获取元素左侧边框的宽度
    //调用getStyle()扩展函数获取边框样式值,并尝试转换为数值,如果转换成功,则赋值。
    //否则判断是否定义了边框样式,如果定义边框样式,且值不为none,则说明边框宽度为默认值,即为3像素。
    //如果没有定义边框样式,且宽度值为auto,则说明边框宽度为0
    var bl = parseInt(getStyle(o, "borderLeftWidth")) || ((o.style.borderLeftStyle && o.style.borderLeftStyle != "none" )? 3 : 0);
    //获取元素顶部边框的宽度,设计思路与获取左侧边框方法相同
    var bt = parseInt(getStyle(o, "borderTopWidth")) || ((o.style.borderTopStyle && o.style.borderTopStyle !="none" ) ? 3 : 0);
    var x = e.offsetX || (e.layerX - o.offsetLeft - bl);  // 一般浏览器下鼠标偏移值
    //兼容Mozilla类型浏览器,减去边框宽度 
    var y = e.offsetY || (e.layerY - o.offsetTop - bt); // 一般浏览器下鼠标偏移值 
    //兼容Mozilla类型浏览器,减去边框宽度 
    var u = navigator.userAgent; // 获取浏览器的用户数据 
    if( (u.indexOf("KHTML") > - 1) ||(u.indexOf("Konqueror") > - 1) || (u.indexOf("AppleWebKit") > - 1) 
    ){ // 如果是Safari浏览器,则减去边框的影响 
        x -= bl; y -= bt; 
    } return { // 返回兼容不同浏览器的鼠标位置对象,以元素边框内壁左上角为定位原点 
        x : x, y : y 
    }   
}
Copy after login

The demonstration effect is as follows:

How to get the position of the pointer in javascript

Recommended learning: javascript video tutorial

The above is the detailed content of How to get the position of the pointer 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)

Location of Origami Bird at Stardome Railway Crocker Film and Television Park Location of Origami Bird at Stardome Railway Crocker Film and Television Park Mar 27, 2024 pm 11:51 PM

There are a total of 20 origami birds in Croaker Film and Television Park on Star Dome Railway. Many players don’t know where the origami birds are in Crocker Film and Television Park. The editor has summarized the locations of each origami bird to help everyone. Search for it, and take a look at this latest summary of the locations of the origami birds in Croaker Film and Television Park for specific content. Guide to the Honkai Star Dome Railway: Origami Bird in Crook Movie Park Location 1, Crook Movie Park 1st Floor 2, and Crook Movie Park 2nd Floor Star Dome Railway

Where is Kuaishou published and how to change its location? How to add a location to a video that has been uploaded? Where is Kuaishou published and how to change its location? How to add a location to a video that has been uploaded? Mar 21, 2024 pm 06:00 PM

As a well-known short video platform in China, Kuaishou provides many creators with opportunities to showcase their talents and share their lives. When uploading a video, some novice creators may be confused about how to change the video posting location. This article will introduce you to how to change the publishing location of Kuaishou videos, and share some tips for Kuaishou video publishing to help you make better use of this platform to showcase your work. 1. Where is Kuaishou published and how to change its location? 1. Publishing interface: In Kuaishou APP, click the &quot;Publish&quot; button to enter the video publishing interface. 2. Location information: In the publishing interface, there is a &quot;Location&quot; column. Click to enter the location selection interface. 3. Change location: In the location selection interface, click the &quot;Location&quot; button to view the current location. If you want to change the location, click &quot;Location&quot;

How do generic functions handle pointers and reference types in Golang? How do generic functions handle pointers and reference types in Golang? Apr 16, 2024 pm 04:06 PM

When a generic function handles pointer types in Go, it will receive a reference to the original variable, allowing the variable value to be modified. Reference types are copied when passed, making the function unable to modify the original variable value. Practical examples include using generic functions to compare strings or slices of numbers.

How to change the location of Gaode Map Home How to change the location of Gaode Map Home Feb 27, 2024 pm 07:31 PM

As a powerful assistant for our daily travels, Amap not only provides accurate navigation services, but also allows users to directly determine their "home location" in a user-friendly manner. It is convenient to check your route home every time. But sometimes the location of our home also needs to be updated, so how can we easily modify the "location of home" in Amap? Next, follow the editor's guide and learn how to modify it together! Amap How to change the location of your home? Answer: [AMAP] - [Settings] - [Three-dot icon] - [Modify location] - [Set location] - [Set as home address]. Specific steps: 1. First open the Amap software, enter the homepage, slide up, find home and click [Settings]; 2. Then in the settings page, we can

Where is the Last Era Arena? Where is the Last Era Arena? Mar 07, 2024 pm 08:16 PM

In "Last Age", players can play in various modes such as game mode, challenge mode, and arena, etc. Arena is the ultimate way to play the game, providing two modes for players to choose from. Where is the Arena in the Last Era? Answer: The Arena is an endgame game, and its specific location is at the Champion's Gate. You need to obtain the Arena Key or Memory Arena Key. After right-clicking, you can see the world map and find the specific location of the Champion's Gate. The arena is divided into two major modes: Arena Championship Mode and Endless Arena Mode. The former includes 40 waves of enemies and selected rewards, always culminating in a battle with the Arena Champion. There are 4 stages in Arena Championship Mode. The higher the difficulty, the better the rewards. Endless Arena is a mode with infinite waves. The difficulty gradually increases. The challenger with the best score will

Where is the Meituan Daily Voucher location_Meituan Daily Voucher location introduction Where is the Meituan Daily Voucher location_Meituan Daily Voucher location introduction Mar 27, 2024 pm 05:11 PM

1. We open Meituan on the mobile phone, and then click on the takeout option in the upper left corner of the homepage. 2. After entering the takeout platform page, you can see the section with daily coupons on the homepage, click on it directly. 3. After entering the Tiantian God Voucher, you will see a lot of activities, click Finish, and then we can get rewards after completing the tasks.

Where can I find the vivo phone screen recording tutorial? Where can I find the vivo phone screen recording tutorial? Mar 23, 2024 am 11:40 AM

1. Swipe down from the top of the phone screen to call out the control center, and click the [Screen Recording] icon to start screen recording. Click the red timing button at the top of the screen to end the screen recording. 2. If it is the first time you use it, it will automatically jump to the screen recording settings. You can make some settings here, such as recording sound, displaying touch tracks, etc., and then click [Start Screen Recording].

List of refresh point locations in Identity V's Forest of No Return Cellar List of refresh point locations in Identity V's Forest of No Return Cellar Mar 08, 2024 pm 12:34 PM

A list of the refresh point locations of the cellar in Identity V’s Forest of No Return. Friends, in the game Identity V, there are not only gates but also cellars. Many friends don’t know where the cellar in the map of Identity V’s Forest of No Return is. Below is Let me tell you. A list of the refresh point locations of Identity V’s Forest of No Return Cellar. The location of the first Forest of No Return Cellar. In the game, the first Forest of No Return Cellar is right behind the big house. The house is double-story and very huge. Players Can be found easily. 2. The location of the second cellar in the Forest of No Return. The location of the second cellar in the Forest of No Return is also near the double-storey big house. After the player enters the big house, he comes to the window on the first floor of the house and pulls out directly from there. I saw a ruin directly opposite. There was a bonfire inside and it was very bright. In the fence of the ruin

See all articles