使用jquery获得单击元素的位置?

时间:2022-10-10 19:10:08

I want to scroll to get an item into view when it's clicked, however I cannot manage to get it's top position on click:

当它被点击时,我想要滚动查看一个条目,但是我无法在点击时获得它的顶部位置:

This is what I'm trying right now:

这就是我现在正在尝试的:

    $( "section" ).click(function(e) {
        console.log("thing top: "+$(this).position().top);
        //$('html,body').animate({ scrollTop: 0 }, 'slow');
        //return false; 
    });

However I always get the same top position, now matter what element is clicked. How can I do this right?

但是我总是得到相同的顶部位置,现在不管点击什么元素。我该怎么做呢?

2 个解决方案

#1


8  

Try $(this).offset().top as it gets the position relative to the document rather than the parent

试(美元).offset()。顶部因为它获得相对于文档而不是父文档的位置

Offset

抵消

#2


0  

scrollTop: $("#elementtoScrollToID").offset().top

#1


8  

Try $(this).offset().top as it gets the position relative to the document rather than the parent

试(美元).offset()。顶部因为它获得相对于文档而不是父文档的位置

Offset

抵消

#2


0  

scrollTop: $("#elementtoScrollToID").offset().top