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

后端 未结 1 475
不知归路
不知归路 2020-12-06 21:07

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

相关标签:
1条回答
  • 2020-12-06 21:55

    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

    0 讨论(0)
提交回复
热议问题