简体   繁体   中英

Scrolling a <div> to Specific Content

I'm creating a split page with a menu on the left, and the main content on the right. When I click on a menu item, I want to scroll the main content to that item.

I found JavaScript scrollTo() , which takes offset arguments.

Is there any way to determine the offset of a particular <p> or other element within a <div> ? Or perhaps there is another way to scroll to an element without knowing its offset?

EDIT

Thanks for the replies. Looks like everyone gave similar answers. However, I ran into a problems with this. It seems that offset().top (or position().top ) return different values depending on the current scroll position.

My jsFiddle is here: http://jsfiddle.net/gBTW9/4/embedded/result/

If I scroll to the top and selection Section 4, it works as expected. But once I've scrolled, it stops working correctly. Can anyone see what is happening.

You can get the vertical offset of an element using $('p').offset().top . You can combine this with scrollTop() using this:

$('div').scrollTop($('p').offset().top);

You need to use position() rather than offset(). If you know the id of that

you can easily find the position of that paragraph tag

jQuery: Difference between position() and offset()

There are jquery methods offset and position stat can help there.

Also there is good scrollTo plugin which accepts elements and much more.

If i didn't misunderstood you just need an animated scrolling to a particular element, something similar on what I did on my portfolio .

Assuming that the menu on the left is fixed, then just scroll the page to the element you want to scroll to:

$("html, body").animate({
   scrollTop: $('#element').offset().top 
});

If you need to move a particular element over another element then:

$("#element1").animate({
   top: $('#element2').offset().top 
});

Why try it the hard way, when you can use a HTML native attribute??

call me old school, but i like to keep it simple.

within your menu:

use:

<ul>
    <li>
        <a href="#Paragraph1">Paragraph 1</a>
    </li>
</ul>

instead of

<ul>
    <li>Paragraph 1</li>
</ul>

this will make your section jump to the # (id) that equals Paragraph1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM