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中文網其他相關文章!