首页 > 解决方案 > Chrome 移动版无法正确更新 CSS 样式

问题描述

我想在将页面滚动到顶部时制作一个固定位置的粘性元素,该元素会粘在页面底部。

它在桌面 Chrome 浏览器上运行正常,但在移动设备上不行。无法找出确切的问题。是 chrome bug,我的代码错了吗?

class App extends React.Component {
    state = {
        position: 0
    }

    componentDidMount() {
       window.addEventListener('scroll', this.handleScroll);
    }


    componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll);
    }

    handleScroll = () => {
        const {scrollTop, scrollHeight} = document.documentElement;
        const scroll = scrollHeight - scrollTop - window.innerHeight;
        if (scroll <= 100) {
            this.setState({position: 100 - scroll});
        } else if (this.state.position !== 0) {
            this.setState({position: 0});
        }

    }

    render() {
        return (
             <section>
                 <div className="box" style={{
                    bottom: this.state.position
                 }}>
                   STICKY BOX
                </div>
             </section>
        );
    }
}

这是笔:Codepen

标签: javascriptreactjsgoogle-chromescroll

解决方案


推荐阅读