2016-12-02 108 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