首頁  >  文章  >  web前端  >  如何在 jQuery 中取得相對於目標元素的精確點擊座標?

如何在 jQuery 中取得相對於目標元素的精確點擊座標?

DDD
DDD原創
2024-11-15 07:47:02202瀏覽

How to Get Precise Click Coordinates Relative to a Target Element in jQuery?

Finding Click Coordinates on Target Element Using jQuery

In order to obtain the precise position of a mouse click on a specific target element, you may consider utilizing either the pageX and pageY properties to determine the position relative to the entire document, or the offset() method to establish the relative position within the specific element.

However, if you require the relative position within the element's parent or another containing element, you may employ the position() method. Here's an example demonstrating the usage of these methods:

$('#element').on('click', function(e) {
  // Determining position relative to document using pageX and pageY:
  var clickX = e.pageX;
  var clickY = e.pageY;

  // Determining position relative to element using offset():
  var offsetX = $(this).offset().left;
  var offsetY = $(this).offset().top;
  var relativeClickX = e.pageX - offsetX;
  var relativeClickY = e.pageY - offsetY;

  // Determining position relative to parent using position():
  var positionX = $(this).position().left;
  var positionY = $(this).position().top;
  var parentRelativeClickX = e.pageX - positionX;
  var parentRelativeClickY = e.pageY - positionY;
});

In the case of your code:

jQuery("#seek-bar").click(function(e){
    var x = e.pageX - e.target.offsetLeft;
    alert(x);    
});

Your intention is to retrieve the position of the mouse cursor relative to the #seek-bar element upon clicking. However, the subtraction of e.target.offsetLeft is incorrect because the offsetLeft property returns the position of the element relative to its parent. Instead, you should utilize e.pageX directly, which provides the x-coordinate relative to the document.

Refer to the provided code demonstration for a more detailed elaboration.

以上是如何在 jQuery 中取得相對於目標元素的精確點擊座標?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn