简体   繁体   English

无论设备大小如何,获取鼠标在图像上单击的坐标(X,Y)

[英]Get Coordinates (X,Y) of mouse click on image regardless of the device size

I have a div with an background image on my website.我的网站上有一个带有背景图片的 div。 I want to mark the place where a user clicked within this div with a red dot.我想用红点标记用户在此 div 中单击的位置。 I use the following code which works partially (the dot gets placed):我使用以下部分工作的代码(放置点):

JS:记者:

    document.getElementById('auto').addEventListener("click", function(event) {
        var test = "a variable";
        var x = event.pageX - this.offsetLeft;
        var y = event.pageY - this.offsetTop;

    $(auto).append($('<div class="damage_dot">'+test+'</div>').css({
                        left: x + 'px',
                        top: y + 'px',
                        }));            

Problem:问题:
the dot never appears at the place where I clicked.该点从未出现在我点击的地方。 If I scroll or try to do the same on a mobile device, the differences between the point where I clicked and the dot are getting bigger.如果我在移动设备上滚动或尝试做同样的事情,我点击的点和点之间的差异会越来越大。


Is there a way to achieve this? 有没有办法做到这一点?
Thanks a lot in advance! 非常感谢!

Please check if this is what you are looking for:请检查这是否是您要查找的内容:

https://plnkr.co/edit/vSdGW5TIGrGYpAdk?open=lib%2Fscript.js https://plnkr.co/edit/vSdGW5TIGrGYpAdk?open=lib%2Fscript.js

 (function(funcName, baseObj) { document.getElementById('auto').addEventListener("click", function(event) { var x = event.clientX; var y = event.clientY; $(auto).append($('<div class="damage_dot">a</div>').css({ left: x + 'px', top: y + 'px', })); // Add your code here }); })("docReady", window);
 .damage_dot{ color:red; position: absolute; height:2px; width: 2px; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM