简体   繁体   English

如何偏移scrollIntoView()

[英]how to offset scrollIntoView()

Working on a React application and have this function which works to scroll to a div, but it is just slightly off so I need to have it scroll up by 20px or so when it goes to the correct div. 在一个React应用程序上工作,并且有这个函数可以滚动到一个div,但它只是稍微关闭所以当它转到正确的div时我需要向上滚动20px左右。

     class CountryDropdown extends Component{

    handleScroll = (country) => {

        document.getElementById(country).scrollIntoView({
            block: "start",
            behavior: "smooth"
          })

      }

    render () {
    return (
        <Dropdown text='Jump to Country'>
            <Dropdown.Menu>
                <Dropdown.Item flag='fr' text='France' onClick={() => this.handleScroll("france")}/>
                <Dropdown.Item flag='es' text='Spain' onClick={() => this.handleScroll("spain")}/>
                <Dropdown.Item flag='pt' text='Portugal' onClick={() => this.handleScroll("portugal")}/>
                <Dropdown.Item flag='gr' text='Greece' onClick={() => this.handleScroll("greece")}/>
                <Dropdown.Item flag='de' text='Germany' onClick={() => this.handleScroll("germany")}/>
                <Dropdown.Item flag='at' text='Austria' onClick={() => this.handleScroll("austria")}/>
            </Dropdown.Menu>
        </Dropdown>
    );
}
}


 export default CountryDropdown;

If its really just 20px, I suppose you could just add an extra DOM event to get it in position. 如果它真的只有20px,我想你可以添加一个额外的DOM事件来使它就位。 Unfortunately, scrollIntoView() does not have any additional parameters that lets you offset it. 不幸的是,scrollIntoView()没有任何其他参数可以让你抵消它。 On the brightside the following code should get the job done without any clunkiness. 在明亮的一面,下面的代码应该完成工作,没有任何笨拙。

handleScroll = (country) => {

    document.getElementById(country).scrollIntoView({
        block: "start",
        behavior: "smooth"
      })

    document.getElementById(country).scrollTop += 20
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM