用鼠标拖动实现React中DIV的滚动?

16

我正在尝试弄清楚如何使用鼠标(按住左键并拖动)滚动 div,但是我找不到任何有用的信息。

如果有人使用过 trello,在模拟横向拖动时,我想使用鼠标代替滚动条。

大多数其他插件都是针对 JQuery 的,我想要一个原生 JavaScript 解决方案或者一个 React 的解决方案。

我看过以下内容:

1. https://github.com/asvd/dragscroll http://asvd.github.io/dragscroll/

但它不允许您选择其中的元素,这也是我需要的。

还有其他适用于 React 的插件吗?


嘿,@pizzae,你找到解决方案了吗?我也在寻找解决相同问题的方法! - Nidhi Dadiya
1个回答

11
  1. 在窗口的mousedown事件中保持MouseDown位置和滚动信息
  2. 在滚动条的鼠标按下事件中添加mousemove监听器
  3. 根据mousemove中的window.clientX和clientY计算scrollLeft和scrollTop
  4. 在窗口的onmouseup监听器中移除mousemove监听器。

class Application extends React.Component {

  state = {isScrolling: false};

  componentWillUpdate = (nextProps, nextState) =>{
     if(this.state.isScrolling !== nextState.isScrolling ) {
       this.toggleScrolling(nextState.isScrolling);
      }
  };

  toggleScrolling = (isEnable) => {
    if (isEnable) {
      window.addEventListener('mousemove', this.onMouseMove);
      window.addEventListener('mouseup', this.onMouseUp);
    } else {
      window.removeEventListener('mousemove', this.onMouseMove);
    }
  };

  onScroll = (event) => {
  };

  onMouseMove = (event) => {
    const {clientX, scrollLeft, scrollTop, clientY} = this.state;
    this._scroller.scrollLeft = scrollLeft - clientX + event.clientX;
    this._scroller.scrollTop = scrollTop - clientY + event.clientY;
  };

  onMouseUp =  () => {
    this.setState({isScrolling: false, 
                   scrollLeft: 0, scrollTop: 0,
                   clientX: 0, clientY:0});
  };

  onMouseDown = (event) => {
    const {scrollLeft, scrollTop} = this._scroller;
    this.setState({isScrolling:true, scrollLeft, scrollTop, clientX:event.clientX, clientY:event.clientY});
  };

  attachScroller = (scroller) => {
    this._scroller = React.findDOMNode(scroller);
  };

  render() {
    return <div className='container'>
      <div className="scroller"
        ref={this.attachScroller}
        onMouseDown={this.onScroll}
        onScroll={this.onMouseMove}
        >
        <div className="child"/>
        </div>
    </div>;
  }
}

/*
 * Render the above component into the div#app
 */
React.render(<Application />, document.getElementById('app'));

有用的库

http://smikhalevski.github.io/react-scroll-box/

https://gist.github.com/gaearon/150fa1bed09c92abdb46

https://github.com/qiaolb/react-dragscroll


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接