点击在div中的位置 [英] Position of click within div

查看:143
本文介绍了点击在div中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取div内单击的位置,以便当我将窗口随鼠标拖动移动而定位时,鼠标光标将恰好位于初始位置(相对于移动窗口)点击发生.

I'm trying to get the position of a click inside a div so that when I position a window as the mouse drag moves it, the mouse cursor will be exactly on the spot (relative to the moving window) where the initial click occurred.

这是窗口:

<div id="PopUp" class="Popup">
  <div id="PopUpTitleBar"><img class="xOut" onclick="ClosePopUp();" src="/images/xOut.png"></div>
  <div class="InnerPopup">
    <!-- <p>Here is the body of a pop up element.</p> -->
    <p id="PopUpBody"></p>
  </div>
</div>

我有以下方法来处理单击和拖动:

And I have these methods to handle the clicking and dragging:

    var firstClick = true;
    var offsetX = 0;
    var offsetY = 0;

    function mouseUp()
    {
        window.removeEventListener('mousemove', divMove, true);
        firstClick = true;
    }

    function mouseDown(e){
        window.addEventListener('mousemove', divMove, true);
    }

    function divMove(e){
        var div = document.getElementById('PopUp');

        if (firstClick == true) {
            offsetX = $('#PopUpTitleBar').offset().left;
            offsetY = $('#PopUpTitleBar').offset().top;
            firstClick = false;
        }

        var spotX = e.pageX - offsetX;
        var spotY = e.pageY - offsetY;

        div.style.top = spotY + 'px';
        div.style.left = spotX + 'px';
    }

这种排序有效,除了我的offsetX和offsetY返回PopUpTitleBar左上角的位置,而不是PopUpTitleBar中单击的位置.

This sorta works, except that my offsetX and offsetY are returning the position of the top left corner of PopUpTitleBar instead of the position of the click within PopUpTitleBar.

如何纠正这个问题,使我的偏移量相对于PopUpTitleBar的左上角?

How can I correct this so my offsets are relative to the inside top left corner of PopUpTitleBar?

谢谢.

推荐答案

您在屏幕上具有点击位置.然后,您将获得div的位置.用div位置减去主要位置,您将获得相对于该div的手指位置.

You have the click position on the screen. And then you have the position of the div. Substract the main position with the div position and youll have the finger position relative to that div.

$('#PopUpTitleBar').click(function (e) {
    var posX = $(this).offset().left, posY = $(this).offset().top;
    alert("e.pageX: " + e.pageX + " posX:" + posX + " e.pageY:" + e.pageY + " posY:" + posY);
});

这篇关于点击在div中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆