DIV auto scroll

后端 未结 5 1039
情话喂你
情话喂你 2021-02-06 10:34

I have a div that has a large number of items in it. I select these items dynamically by clicking a button, overflow is auto in my case. What I want is that when an item that is

相关标签:
5条回答
  • 2021-02-06 11:23

    Yet another option is to use jQuery along with the plugin ScrollTo.

    0 讨论(0)
  • 2021-02-06 11:23

    Yet another option... anchors.

    Assign each item a unique ID, and when you want to scroll to a particular item, execute the following JavaScript code:

    location.hash = itemID;
    

    ...where itemID is a variable that contains the ID of the element you want to scroll to.

    Steve

    0 讨论(0)
  • 2021-02-06 11:24

    You could also use the DIV's scrollTop or scrollLeft property (depending on if the scroll is horizontal or vertical).

    I've done this before and used a setTimeout event to make it scroll fluidly, rather than in 1 motion. This is without JQuery tho.

    0 讨论(0)
  • 2021-02-06 11:25

    When your button clicked and an item selected call this selected item's focus() method. this will cause auto scroll to your element :

    <div style="height:80px; overflow:auto;">
        <input type="text" id="id1"><br><br>
        <input type="text" id="id2"><br><br>
        <input type="text" id="id3"><br><br>
        <input type="text" id="id4"><br><br>
        <input type="text" id="id5"><br><br>
        <input type="text" id="id6"><br><br>
    </div>
    <input type="button" onclick="document.getElementById('id6').focus();">  
    
    0 讨论(0)
  • 2021-02-06 11:30

    You can use the scrollTop property of HTMLElement to set the amount its content is scrolled by.

    And you can get the amount you need to scroll by from offsetTop of the element to which you want to scroll.

    For example with this HTML:

    <div id="container">
      <p id="item-1">foo</p>
      <p id="item-2">bar</p>
      <p id="item-3">baz</p>
    </div>
    

    You could use this JavaScript to scroll the container div to third paragraph:

    document.getElementById("container").scrollTop = document.getElementById("item-3").offsetTop;
    
    0 讨论(0)
提交回复
热议问题