通过拖动鼠标来反应滚动div?

时间:2016-12-02 06:32:27

标签: javascript html reactjs

我想弄清楚如何使用鼠标滚动div(左手拖动和拖动),但我找不到任何有用的东西。

如果有人使用了trello,我会尝试模拟使用鼠标而不是滚动条水平拖动的功能。

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

我看过:

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

但它不允许你选择里面的元素,这也是我需要的东西。

React还有其他合适的插件吗?

1 个答案:

答案 0 :(得分:4)

  1. 维护MouseDown位置并滚动信息onmousedown of window
  2. 在滚动条的mousedown上添加mousemove侦听器
  3. 根据mousemove
  4. 中的窗口clientX和clientY计算scrollLeft和scrollTop
  5. 删除窗口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'));
    
  6. 有用的图书馆

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

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

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