jQuery Mouse Events: PageX Y vs. ClientX Y - gitbbln/gitbbln.github.io GitHub Wiki

When I first starting playing with jQuery events, a lot of what I learned about the jQuery Event object was through trial and error. While I could be remembering incorrectly, I used to find that the jQuery documentation was good at describing the event handlers, but not so good at describing the event object; as such, while I knew that the jQuery event object was a standardized event object, I was never 100% sure which parts of it I was supposed to be using. Когда я впервые начал играть с событиями jQuery, многое я узнал об объекте события jQuery методом проб и ошибок. Хотя я мог вспомнить неправильно, раньше я обнаруживал, что документация jQuery хороша для описания обработчиков событий, но не очень хороша для описания объекта события; Таким образом, хотя я знал, что объект события jQuery является стандартизированным объектом события, я никогда не был на 100% уверен, какие его части я должен был использовать.

Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).

To see the difference between these two coordinate systems, I set up a page that would log mouse click events against a visible coordinate grid.

Путем проб и ошибок я начал использовать координаты мыши clientX и clientY в объекте события jQuery. Эти координаты дали мне смещение X и Y мыши относительно верхнего левого угла окна просмотра браузера. Однако, читая Справочное руководство jQuery 1.4 Карла Сведберга и Джонатана Чаффера , я заметил, что они часто ссылаются на координаты pageX и pageY. После проверки обновленной документации jQuery я увидел, что это координаты, стандартизированные jQuery; и я увидел, что они дали мне смещение X и Y мыши относительно всего документа (а не только порта просмотра).

Чтобы увидеть разницу между этими двумя системами координат, я создал страницу, которая будет регистрировать события щелчка мыши по видимой координатной сетке.

<!DOCTYPE HTML>
<html>
<head>
	<title>jQuery Mouse Events: ClientX vs. PageX</title>
	<style type="text/css">
		div.grid {
			border: 1px solid #CCCCCC ;
			cursor: pointer ;
			font: 10px verdana ;
			height: 99px ;
			position: absolute ;
			width: 99px ;
			z-index: 100 ;
			}
	</style>
	<script type="text/javascript" src="jquery-1.4.2.js"></script>
	<script type="text/javascript">
		// I draw the grid on the document.
		function createGrid(){
			var body = $( "body" );
			// Draw the X axis.
			for (var x = 0 ; x <= 2000 ; x += 100){
				// Draw the Y axis.
				for (var y = 0 ; y <= 2000 ; y += 100){
					$( "<div class='grid'></div>" )
						.appendTo( body )
						.css({
							left: (x + "px"),
							top: (y + "px")
						})
						.text( x + "," + y )
					;
				}
			}
		};
		// When the DOM is ready, initialize the scripts.
		jQuery(function( $ ){
			// Create the grid for coordinate affordance.
			createGrid();
			// Bind the mouse event to the document so that we
			// can see what kind of coordinates we have to play
			// with.
			$( document ).click(
				function( event ){
					// Client variables.
					console.log(
						"clientX/Y: " +
						event.clientX + ", " +
						event.clientY
					);
					// Page variables. NOTE: These are the ones
					// that are officially supported by the
					// jQuery Event object.
					console.log(
						"pageX/Y: " +
						event.pageX + ", " +
						event.pageY
					);
					// Hrule.
					console.log( "......" );
				}
			);
		});
	</script>
</head>
<body>
	<!-- Nothing needed here. -->
</body>
</html>

As you can see, I create a 2000 x 2000 pixel grid that will give me both horizontal and vertical scrolling. And, when I scroll both right and down, and then click on the document, I get the following console output:

Как видите, я создаю сетку размером 2000 x 2000 пикселей, которая дает мне как горизонтальную, так и вертикальную прокрутку. И когда я прокручиваю вправо и вниз, а затем нажимаю на документ, я получаю следующий вывод консоли:

As you can see, the clientX and clientY coordinates give me the mouse position relative to the view port, regardless of the scroll of the document. The pageX and pageY coordinates, on the other hand, give me the mouse position relative to the top, left of the entire document, again regardless of the scrolling.

Which mouse event coordinates you should be using is not really a question for debate - the pageX and pageY coordinates are the ones that have been standardized by jQuery. In order to keep your code as cross-browser compatible as possible, you should rely on pageX and pageY. It is unfortunate that I did not know about this until just recently - I am quite sure that I have posted a lot of code that accidentally relied on the proprietary event properties, clientX and clientY.

Как видите, координаты clientX и clientY дают мне положение мыши относительно порта просмотра, независимо от прокрутки документа. С другой стороны, координаты pageX и pageY дают мне положение мыши относительно левого верхнего угла всего документа, опять же независимо от прокрутки.

Какие координаты событий мыши вы должны использовать, на самом деле не является вопросом для обсуждения - координаты pageX и pageY - это те координаты, которые были стандартизированы jQuery . Чтобы ваш код был максимально кроссбраузерным, вы должны полагаться на pageX и pageY. К сожалению, я не знал об этом до недавнего времени - я совершенно уверен, что опубликовал много кода, который случайно использовал проприетарные свойства событий clientX и clientY.

⚠️ **GitHub.com Fallback** ⚠️