最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - scrollTop to active element in a overflow scroll div - Stack Overflow

programmeradmin3浏览0评论

I have a specific question about .scrollTop. I have a div with a specific height and a lot of p tags inside:

<div id="scroll">
   <p>name1</p>
   <p>name2</p>
   <!-- till name50 -->
</div>

depending on the name you click it gets a class .active. What I then want to do is scroll the div so, that the name is at the top. So what I get is that I can use scrollTop in an animate function like this:

$('#scroll').animate({scrollTop: value });

but how can I get the var value. I tried it with

var value = $('#scroll p').hasClass('active').position().top;

But somehow it does not work.

Some help is much appreciated.

I have a specific question about .scrollTop. I have a div with a specific height and a lot of p tags inside:

<div id="scroll">
   <p>name1</p>
   <p>name2</p>
   <!-- till name50 -->
</div>

depending on the name you click it gets a class .active. What I then want to do is scroll the div so, that the name is at the top. So what I get is that I can use scrollTop in an animate function like this:

$('#scroll').animate({scrollTop: value });

but how can I get the var value. I tried it with

var value = $('#scroll p').hasClass('active').position().top;

But somehow it does not work.

Some help is much appreciated.

Share Improve this question asked May 13, 2014 at 21:45 supersizesupersize 14.9k19 gold badges85 silver badges144 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

You need to check scrollTop() for the container #scroll and add that back to the position() arg.

var $scroll = $('#scroll');

$('p').click(function(e){
    var $this = $(this);
    $scroll.animate({
        "scrollTop": $this.position().top + $scroll.scrollTop()
    }, 1000);
});

http://jsfiddle/yCEap/1/

To just get the value:

var value = $('#scroll').scrollTop();
发布评论

评论列表(0)

  1. 暂无评论