【问题标题】:add scroll listener by id按 id 添加滚动侦听器
【发布时间】:2019-12-26 09:06:28
【问题描述】:

您好,我无法通过 id 添加滚动侦听器,它适用于 WINDOW,但不适用于自定义滚动元素。 这是我的代码:

componentDidMount() {
    const scrollPanel = document.getElementById('scrollPanel');
    scrollPanel.addEventListener('scroll', this.listenToScroll);
  }

componentWillUnmount() {
    const scrollPanel = document.getElementById('scrollPanel');
    scrollPanel.removeEventListener('scroll', this.listenToScroll);
  }

listenToScroll = () => {
    const { position } = this.state;
    const scrollPanel = document.getElementById('scrollPanel');
    const winScroll = scrollPanel.scrollTop;
    const height =
         scrollPanel.scrollHeight -
         scrollPanel.clientHeight;

    const scrolled = winScroll / height;
    console.log('scrolled', scrolled);
    this.setState({
      position: scrolled,
    });

当我尝试检查某个值时,它永远不会改变

【问题讨论】:

    标签: reactjs dom listener


    【解决方案1】:

    在创建滚动元素的元素内部必须有一个事件处理程序: 在您的情况下,将componentDidMount() 更改为以下:

    componentDidMount() {
            document.addEventListener(
                "scroll",
                this.listenToScroll,
                true // Capture event
            );
        }
        listenToScroll = () => {
            //Your custom code
            alert("click triggered");
        };
    

    我试过了,效果很好

    您可能想查看我从中获得参考的答案: https://stackoverflow.com/a/30475606

    【讨论】:

      猜你喜欢
      • 2011-08-21
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多