Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

html - Scrolling to an anchor within a DIV on external click, via jQuery

I have a scrolling division which contains a list of hotels, grouped alphabetically. Above this division, I have an alphabetical index of links, which when clicked, I would like the corresponding alphabetical item to scroll upwards, within the division.

I've spent about an hour scouring the web and trying various techniques, and haven't found anything that does what I'm looking for, or at least something I can understand; I'm no jQuery genius.

Any assistance would be much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want is element.scrollIntoView(); this will scroll the browser window/div to make an element visible on the page.

An example of this: fiddle link

Update: Added a more complete dynamic example.

CSS

#container {
    overflow: auto;
    height: 50px;
}

.scrollto {
    color: blue;
    text-decoration: underline;  
    cursor: pointer;
}

HTML

<span class="scrollto">a</span>  <span class="scrollto">e</span> <span class="scrollto">i</span>

<div id='container'>
    <div id="a">a</div>
    <div id="b">b</div>
    <div id="c">c</div>
    <div id="d">d</div>
    <div id="e">e</div>
    <div id="f">f</div>
    <div id="g">g</div>
    <div id="h">h</div>
    <div id="i">i</div>
</div>

JS?

$('.scrollto').click(function() {
   $('#' + $(this).text()).get(0).scrollIntoView();
   // or $('#' + $(this).text())[0].scrollIntoView();
});

Basically in this example I created a small overflowed div causing it to have a scrollbar.

I then use id anchors on div tags inside of it to label the different areas in it. I have a span outside the div to auto scroll to a certain anchor point inside the overflowed div when clicked.


@Wayne Smallman: As per the html code in your comment, this is what you would use

$('div#index ul li a').click(function() {
    $($(this).attr('href')).get(0).scrollIntoView();
});

Fiddle Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...