2016-12-02 81 views
3

我想弄清楚如何使用鼠标滚动浏览div(左按住并拖动),但我找不到任何有用的东西。通过拖动鼠标来反应滚动div?

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

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

我已经看过:

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

但它不会让你选择它里面的元素,这是一件好事,我也需要。

有没有其他适合React的插件?

回答

2
  1. 维护的MouseDown位置和滚动信息onmousedown事件窗口的
  2. 添加鼠标移动监听器上滚动的鼠标按下
  3. 计算scrollLeft和scrollTop的根据对窗口的onmouseup监听器窗口clientX和clientY在鼠标移动
  4. 删除鼠标移动。

    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