开发者

Scroll to a particular element w/ jQuery

开发者 https://www.devze.com 2023-01-06 17:34 出处:网络
I have a long list of nested divs.I am passing the ID of a particular element (actually a paragraph element) on the querystring and opening its div and parent onload.However, the list is so long, some

I have a long list of nested divs. I am passing the ID of a particular element (actually a paragraph element) on the querystring and opening its div and parent onload. However, the list is so long, sometimes the element that opens is hidden below the bottom of the window.开发者_运维百科

How do I automatically scroll the user's browser window so that the displayed element is at the top of the screen?

You probably don't need this, but for the record... my list looks like this:

<div id="div1">
    <p id="1"></p>   
    <div>stuff</div>
    <p id="2"></p>   
    <div>stuff</div>
    <p id="3"></p>   
    <div>stuff</div>
</div>
...
<div id="divN">
    <p id="997"></p>   
    <div>stuff</div>
    <p id="998"></p>   
    <div>stuff</div>
    <p id="999"></p>   
    <div>stuff</div>
</div>


You could use the scrollIntoView function.

$(document).ready(function() {
  $('#divN').get(0).scrollIntoView();
});


jQuery:

$(document).ready(function(){
   $(document.body).scrollTop($('#divN').offset().top);
});


The easiest way to do this is by using Ariel Flesler's scrollTo plugin. I've used it a few times before and it is small, lightweight and works very well.

0

精彩评论

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