开发者

get mouse position with respect to parent element

开发者 https://www.devze.com 2022-12-24 20:00 出处:网络
this is my setup <div id=\"uxcParent\"> <div id=\"uxcClickable\"></div> </div> now when a user clicks in the inner element i want the mouse position with respect to the par

this is my setup

<div id="uxcParent">
 <div id="uxcClickable"></div>
</div>

now when a user clicks in the inner element i want the mouse position with respect to the parent div and not the page.

this what i tried.

 var x= e.pageX- obj.offsetLeft;
 var y= e.pageY- obj.offsetTop;

this works fine only when i don't scroll the page. I want the function to return the same values no matter where my elements are on the same page.

update:

i think it was not clear enough. am detailing more now..

consider that the elements are in the document in x position with respect to the document. 开发者_如何学Cthe page has a scroll bar. now i can scroll to any part of the page and the position is still going to be x. but the position with respect to the view port would have changed. so pageX and pageY will give different values. this is my catch.

my elements can be anywhere in the view port and when i go over the inner element i should get co-ordinates with respect to the parent only(should not be influenced by where the parent is)

hope i am clear now.


You can do this using jquery like this:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
   $("#special").click(function(e){
      $('#status2').html(e.pageX +', '+ e.pageY);
   }); 
})
</script>
<body>

<h2 id="status2">
0, 0
</h2>
<div style="width: 100px; height: 100px; background:#ccc;" id="special">
Click me anywhere!
</div>
</body>
</html>

Note that the pixel values give are relative to the entire document. If you want to calculate the position within a particular element, or within the viewport, you can look at offsetY and offsetX, and do a bit of arithmetic to find the relative value.

Here is an example of finding the position within the particular element rather than the page:

$("#special").click(function(e){

    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;

      alert(x +', '+ y);
   });

Where "special" is the id of the inner element.


That is interesting, I think this document can help you a lot.


If scrolling was the only thing messing you up then I would think adding in scrollLeft and scrollTop would fix the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消