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

后端 未结 1 478
不知归路
不知归路 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

    a  e i
    
    
    a
    b
    c
    d
    e
    f
    g
    h
    i

    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)
提交回复
热议问题