Scrolling to a element inside a scrollable DIV with pure Javascript

前端 未结 3 899
星月不相逢
星月不相逢 2020-11-29 03:56

I have a div that has overflow: scroll and I have some elements inside the DIV that are hidden. On click of a button on the page, I want to make the DIV scroll

3条回答
  •  我在风中等你
    2020-11-29 04:36

    You need to read the offsetTop property of the div you need to scroll to and then set that offset to the scrollTop property of the container div. Bind this function the event you want to :

    function scrollToElementD(){
        var topPos = document.getElementById('inner-element').offsetTop;
        document.getElementById('container').scrollTop = topPos-10;
    }
    div {
        height: 200px;
        width: 100px;
        border: 1px solid black;
        overflow: auto;
    }
    
    p {
        height: 80px;
        background: blue;
    }
    #inner-element {
        background: red;
    }

    A

    B

    C

    D

    E

    F

    function scrollToElementD(){
      var topPos = document.getElementById('inner-element').offsetTop;
      document.getElementById('container').scrollTop = topPos-10;
    }
    

    Fiddle : http://jsfiddle.net/p3kar5bb/322/ (courtesy @rofrischmann)

提交回复
热议问题