[英]Mouse click coordinates relative to the parent div's top left corner
How to get mouse click coordinates relative to the parent div's top left corner instead of top left corner of the browser's viewport ? 如何获得相对于父div左上角而非浏览器视口左上角的鼠标单击坐标?
Example : If you click on #mydiv
in the code below, how to get the coordinates relative to #mydiv
's top left corner? 示例 :如果在下面的代码中单击#mydiv
,如何获取相对于#mydiv
左上角的坐标?
mydiv.onclick = function(e) { alert(e.clientX + ' ' + e.clientY); }
#blah { position: absolute; top:50px; left:60px; width: 1000px; height: 1000px; background-color: #F0F } #mydiv { position: absolute; top:100px; left:100px; width: 100px; height: 100px; background-color: #FF0 }
<div id="blah"><div id="mydiv">Blah</div></div>
Edited (there was a major mistake in the example). 编辑(该示例中存在一个主要错误)。
Try it: 试试吧:
mydiv.onclick = function(e) {
var offsets =element_offsets(this.parentNode);
alert(e.clientX-offsets.left);
alert(e.clientY-offsets.top);
}
function element_offsets(e) {
var left = 0, top = 0;
do {
left += e.offsetLeft;
top += e.offsetTop;
} while (e = e.offsetParent);
return { left: left, top: top };
}
Below is my code, sorry for using JQuery : but it gives the coordinates of parent element relative to #mydiv
. 以下是我的代码,抱歉使用JQuery:但是它给出了相对于#mydiv
的父元素的坐标。
$('#mydiv').on('click', function(e) {
var offs = $('#mydiv').offset();
alert((e.clientX - offs.left) + ' ' + (e.clientY - offs.top));
});
See the script and example from this page: 请参阅此页面上的脚本和示例:
http://coursesweb.net/javascript/get-mouse-coordinates-inside-div-image_s2 http://coursesweb.net/javascript/get-mouse-coordinates-inside-div-image_s2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.