How can I scroll a div to be visible in ReactJS?

前端 未结 9 1527
梦如初夏
梦如初夏 2020-12-04 15:25

I have a popup list which is a div that contains a vertical list of child divs. I have added up/down keyboard navigation to change which child is

9条回答
  •  失恋的感觉
    2020-12-04 16:11

    In you keyup/down handler you just need to set the scrollTop property of the div you want to scroll to make it scroll down (or up).

    For example:

    JSX:

    {content}

    keyup/down handler:

    this.refs.foo.getDOMNode().scrollTop += 10

    If you do something similar to above, your div will scroll down 10 pixels (assuming the div is set to overflow auto or scroll in css, and your content is overflowing of course).

    You will need to expand on this to find the offset of the element inside your scrolling div that you want to scroll the div down to, and then modify the scrollTop to scroll far enough to show the element based on it's height.

    Have a look at MDN's definitions of scrollTop, and offsetTop here:

    https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

提交回复
热议问题