简体   繁体   English

jQuery如何使用事件坐标对齐div?

[英]jQuery how to align a div using event coordinates?

I have a map with Earth and I want to set the marker exactly where the user is clicking (like on google maps). 我有一张包含Earth的地图,我想将标记设置为用户正要点击的位置(例如在Google地图上)。

<div class='map_wrapper'>
<div class='marker'></div>
    <img src="images/map.jpg" alt="" usemap="#world_map" />

    <map name="map_coords" id='world_map'>
<area shape="poly" class='europe' name="Europe" coords="468,186,468,191,463,194,460,199,458,205" />

    </map>
</div>

<style type='text/css'>
.map_wrapper { position:relative; }
.marker {
   position:absolute;
   width:25px;
   height:34px;
   background:url(../images/marker.png) top center no-repeat;
   z-index:2;
}
</style>

And the javascript 和JavaScript

$(document).ready(function(){
    $('.map_wrapper area').click(function(ev){
        var offset = $(this).offset();
        var mObj = $('.marker');

        mObj.css({
            'margin-left' : (ev.clientX - offset.left - (mObj.width()/2) ) + 'px',
            'margin-top' : (ev.clientY - offset.top) + 'px'
        });
    });
});

Applying margin-left for the marker is working, I'm having problem with the Y (vertical) alignment. 将左边距留给标记有效,Y方向(垂直)存在问题。 I don't know how to calculate px from margin-top. 我不知道如何从边距顶部计算px。

You can get the mouse position where the user clicks from the event.pageX and event.pageY. 您可以从event.pageX和event.pageY获取用户单击的鼠标位置。 The figures will give you an absolute position from the top left of the document. 这些数字将为您提供从文档左上方开始的绝对位置。 If you move the marker to the top of the document then you can simply use those values. 如果将标记移到文档顶部,则只需使用这些值即可。 Otherwise you'll need to take off the top and left of the relative container. 否则,您需要取下相对容器的顶部和左侧。

$(document).ready(function(){
    $('.map_wrapper area').click(function(ev){
        var mObj = $('.marker');

        mObj.css({
            'left' : ev.pageX + 'px',
            'top' : ev.pageY + 'px'
        });
    });
});

At the moment this will only work if you click inside Europe. 目前,这仅在您单击欧洲内部时才有效。 If you want to be able to click anywhere then attach the event to the image and you can get rid of the map. 如果您希望能够单击任意位置,则将该事件附加到图像上,就可以摆脱地图。

http://docs.jquery.com/Tutorials:Mouse_Position http://docs.jquery.com/Tutorials:Mouse_Position

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

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