当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to get the position of a clicked element

问题描述:

I've got a parent div in my dom hierarchy and around 100 sub elements inside the parent div. I've binded a click event on each sub element. what I want is the position of sub element from the top of the parent element. I used jquery .position nd .offset but both return the position from the top of the page. The parent div is scrollable which means the offlow is hidden. so subtracting top position from the position of the clicked element is not going to work! Can anyone suggest me a work around for this!

网友答案:

Add a position: relative; style to the parent element:

HTML:

<div style="position: relative">
    <div style="position: absolute; top: 200px; left: 200px;" id="clicker">Click Me</div>    
</div>

Javascript:

$(function() {
    $("#clicker").click(function() {
        var $clicker = $(this);
        var pos = $clicker.position();
       console.log(pos.top);
        console.log(pos.left);
    });
});

http://jsfiddle.net/LaEsw/

网友答案:

.offset() returns the position relative to the document, while .position() returns the position relative to the offset parent. .position() would be what you want here, but you need the parent to be "positioned" (having a position other than static, like relative, fixed or absolute). Otherwise, the nearest positioned parent would be the document itself and .position() will act like .offset()

Add position:relative to the parent you want to base the position of your element.

分享给朋友:
您可能感兴趣的文章:
随机阅读: