search
HomeWeb Front-endJS Tutorialjavascript event object coordinate event description_javascript skills

Test browser versions:

IETester 6,7
IE 8.0
Firefox 3.5.5
Chrome 4.1.249.1064 (45376)
Opera 9.64
Safari 4.0


Let’s first take a look at the coordinate attributes of each mainstream browser and their meaning

In IE

event.offsetX
event.offsetY
Coordinates relative to e.srcElement
Sets or gets the x coordinate of the mouse pointer position relative to the object that triggered the event.
Set or get the y coordinate of the mouse pointer position relative to the object that triggered the event.


event.clientX
event.clientY
Always relative to the viewport
Sets or gets the x-coordinate of the mouse pointer position relative to the client area of ​​the window, where the client area is not included The window's own controls and scroll bars.
Set or get the y coordinate of the mouse pointer position relative to the client area of ​​the window, where the client area does not include the window's own controls and scroll bars.


event.x
event.y
Although the manual says it is relative to the document, in ie6/7, their values ​​are consistent with clientX and clientY
But this It is not a serious problem, because the relative coordinates of the viewport and the height of the scroll bar have been rolled out, and the real x(y) can still be obtained. This problem is solved in the standard mode of ie8

Set or get the mouse The x-pixel coordinate of the pointer position relative to the parent document.
Set or get the y pixel coordinate of the mouse pointer position relative to the parent document.

event.screenX
event.screenY
Set or get the x coordinate of the mouse pointer position relative to the user's screen.
Set or get the y coordinate of the mouse pointer position relative to the user's screen.

In FireFox

event.layerX
event.layerY
Coordinates relative to e.srcElement
Sets or gets the x of the mouse pointer position relative to the object that triggered the event coordinate.
Set or get the y coordinate of the mouse pointer position relative to the object that triggered the event.

event.clientX
event.clientY
Always relative to the viewport
Sets or gets the x coordinate of the mouse pointer position relative to the client area of ​​the window, where the client area does not include the window itself Controls and scroll bars.
Set or get the y coordinate of the mouse pointer position relative to the client area of ​​the window, where the client area does not include the window's own controls and scroll bars.


event.pageX
event.pageY
Sets or gets the x-pixel coordinate of the mouse pointer position relative to the parent document.
Set or get the y pixel coordinate of the mouse pointer position relative to the parent document.


event.screenX
event.screenY
Set or get the x coordinate of the mouse pointer position relative to the user's screen.
Set or get the y coordinate of the mouse pointer position relative to the user's screen.


In fact, IE and Firefox have included all the attributes. Other browsers combine these attributes, but the meaning is exactly the same

Chrome and Safari
Chrome and The two Safari brothers are very thorough. They include all coordinate attributes, including

event.offsetX
event.offsetY
event.layerX
event.layerY

event.clientX
event.clientY

event.x
event.y
event.pageX
event.pageY

Note: Chrome and Safari The performance of event.x event.y is consistent with IE6 7, they are equal to event.clientX, event.clientY


Opera has firmly followed the path of ie6 7, it has

event.offsetX
event.offsetY

event.clientX
event.clientY

event.x
event.y
Almost exactly the same as ie, luckily It has pageX, pageY
event.pageX
event.pageY

Note: Chrome and Safari, as well as Opera's event. clientX, event.clientY are equal,
And in ie8, event.x, event.y are equal to event.pageX, event.pageY of other browsers


Why is layerX and Will offsetX, x, and pageX appear repeatedly in some browsers?
Because W3C has not standardized these attributes, the MouseEvent part in the DOM3 draft follows the definition of DOM2. There are only two pairs of attributes

clientX of type long, readonly
The horizontal coordinate at which the event occurred relative to the viewport associated with the event.
clientY of type long, readonly
The vertical coordinate at which the event occurred relative to the viewport associated with the event

screenX of type long, readonly
The horizontal coordinate at which the event occurred relative to the origin of the screen coordinate system.
screenY of type long, readonly
The vertical coordinate at which the event occurred relative to the origin of the screen coordinate system.

This is a failure, so the browsers that support the standard have no direction. But, the browser manufacturers second thought, W3C can't figure it out anyway, they must start from offsetXY and layerXY,
Choose one between pageXY and xy, so in order to meet the standard, both pairs of attributes are put into the browser.

No matter what, problems must be solved.After seeing the compatibility report above, the prototype of the code is ready

Let’s start writing!

getEventCoord

Copy code The code is as follows:

1 var getEventCoord = function ( e )
2 {
3 var evt = e||event;
4 var html = document.documentElement; //Scroll bar on
5 return {
6
7 //If the pageX attribute is true, use pageX, otherwise use clientX html.scrollLeft
8 pageX : evt.pageX || evt.clientX html.scrollLeft,
9
10 / /If the pageY attribute is true, use pageY, otherwise use clientY html.scrollTop
11 pageY : evt.pageY || evt.clientY html.scrollTop,
12
13 //clientX Y Everyone agrees , no suspense
14 clientX : evt.clientX,
15 clientY : evt.clientY,
16
17 //If the layerX attribute is true, use layerX, otherwise use offsetX
18 layerX : evt.layerX || evt.offsetX,
19
20 //If the layerY attribute is true, use layerY, otherwise use offsetY
21 layerY : evt.layerY || evt.offsetY
22 }
23 }


Usage is as follows
Copy code Code As follows:

document.onmousemove = function( e )
{
var coord = getEventCoord(e);
document.title = [coord.pageX,coord.pageY] ;
}


It looks pretty good and can meet the needs of daily work, but there are still several problems

1. Not rigorous

Use evt.pageX || evt.clientX html.scrollLeft to judge,
As long as evt.pageX is equal to undefined, null, NaN, '', 0, false these values, the expression on the left will result It is false, thus calculating the expression on the right and returning the value of the expression,
and evt.pageX itself has a chance to return 0. So this judgment should be changed to
typeof evt.pageX == 'number' ? evt.pageX : evt.clientX html.scrollLeft
We only use it when pageX is a number

2. Cannot work in weird mode

What is weird mode?

In order to be compatible with versions before IE56, IE introduced two rendering modes in ie6: Quicks Mode (Quicks Mode) and Standard Mode ( Standards Mode)
The difference between the two modes is mainly concentrated in the box model interpretation of CSS, and in BOM. It means that the dependent object of the scroll bar has changed
In weird mode, the scroll bar belongs to the body. If you want to get the height and width of the scroll bar, you need to use document.body.scrollTop
and in standard mode You need to use document.documentElement.scrollTop

and the switching method between the two modes is mainly determined by doctype, see: http://dancewithnet.com/2009/06/14/activating-browser-modes- with-doctype/

Starting from IE6, IE uses a property document.compatMode to detect whether the document is switched to weird mode or in standard mode
If the value of document.compatMode
is BackCompat: that’s it In quirks mode
is CSS1Compat: in standard mode


So in order to work properly in both modes,
we need to determine which mode document.compatMode is
The judgment method is also very simple. You only need to judge whether the first letter of the compatMode value is b, and then you can select the dependent object of scrollTop
The judgment method can be written like this
document.compatMode.indexOf('b ')==0
You can also use regular expressions to write
/^b/i.test( document.compatMode )
The second one is more awesome. . Well, just use the second version (actually the first one performs better)

Now let’s write the second version

Code
Copy code The code is as follows:

var getEventCoord = function( e )
{
var evt = e||event, d = document ,
scrollEl = /^b/i.test( d.compatMode ) ? d.body : d.documentElement,
supportPage = typeof evt.pageX == 'number',
supportLayer = typeof evt. layerX == 'number'
return {
pageX : supportPage ? evt.pageX : evt.clientX scrollEl.scrollLeft,
pageY : supportPage ? evt.pageY : evt.clientY scrollEl.scrollTop,
clientX : evt.clientX,
clientY : evt.clientY,
layerX : supportLayer ? evt.layerX : evt.offsetX,
layerY : supportLayer ? evt.layerY : evt.offsetY
}
}


Boom boom boom, that’s it. What can this function do? The first thing that comes to mind is drag and drop. Let’s write a small drag and drop function to verify it. Next

code
Copy code The code is as follows:

function dragMe( o )
{
var supportCapt = !!o.setCapture;
o.onmousedown = function(e)
{
var coord = getEventCoord( e), x = coord.layerX, y = coord.layerY;
if( supportCapt ) o.setCapture();
document.onmousemove = function(e)
{
var coord = getEventCoord (e);
o.style.left = coord.pageX - x 'px';
o.style.top = coord.pageY - y 'px';
}
document.onmouseup = function()
{
this.onmousemove = this.onmouseup = null;
if( supportCapt ) o.releaseCapture();
}
}
}
dragMe ( document.getElementById('block') );

Example

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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.