简体   繁体   English

使用click.box的CENTER作为原点保存鼠标单击坐标

[英]Saving mouse-click coordinates with the CENTER of click.box as origin

I am trying to write bits of code in an html webpage, so that when the user clicks the mouse within my ClickBox, the X and Y coordinates are saved and then sent to my database. 我正在尝试在html网页中编写一些代码,以便当用户在ClickBox中单击鼠标时,将保存X和Y坐标,然后将其发送到我的数据库。

But for now, the click handler... Here is how far I have got: 但是现在,单击处理程序...这是我得到的结果:

<body>
    <div id = "ClickBox" style = "left:100px;"> </div>
</body>



<script>
    $( document ).ready( function(e)
    {
            $( '#ClickBox' ).click( function(e)
        {
                alert( e.pageX + ' , ' + e.pageY );
        });
    });
</script>



<style type="text/css">
     #ClickBox { width:640px; height:480px; cursor:pointer; background:#2f2f2f; top:50px; color:#fff; font:bold 12px Arial; }
</style>

It works, but displays the click coordinates in a way that is obvious the origin is not the center or top left corner of my ClickBox. 它可以工作,但是以一种显而易见的方式显示点击坐标,即原点不是我的ClickBox的中心或左上角。 How do I modify these snippets, so that regardless of where my ClickBox is located on my webpage, I always get the precise coordinates with the center of my ClickBox being the coordinate origin ? 如何修改这些代码段,以便无论我的ClickBox位于网页上的什么位置,总能获得以ClickBox中心为坐标原点的精确坐标?

Thanks in advance, 提前致谢,

e.pageX and a.pageY are the position of four cursor in the page not a specific div. e.pageX和a.pageY是页面中四个光标的位置,而不是特定的div。

but you can get the mouse position in the div removing the top and the left distance of your div from the body 但您可以在div中获得鼠标位置,从而将div离开身体的顶部和左侧距离

You need to remove the offset of the div: 您需要删除div的偏移量:

Demo 演示版

$( '#ClickBox' ).click( function(e){
    var coordX = e.pageX - $(this).offset().left,
        coordY = e.pageY - $(this).offset().top;
    alert( coordX + ' , ' + coordY );
});

Coordinates relative to top and left. 相对于顶部和左侧的坐标。

coordX = e.pageX - $('#clickbox').offset().left;
coordY = e.pageY - $('#clickbox').offset().top;

To get coordinates with CENTER of Clickbox as origin 以Clickbox的CENTER作为原点获取坐标

coordX = e.pageX - $('#clickbox').offset().left - ($('#clickbox').width() * 0.5);
coordY = e.pageY - $('#clickbox').offset().top - ($('#clickbox').height() * 0.5);

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

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