ui參考primeNG:
http://primefaces.org/primeng...
ts開發環境:
https://github.com/lycHub/ts-...
目錄
說明
ui參考primeNG
已實現的功能:git
- 雙向滑動
- 禁止某條邊滑動
- 同時支持移動、pc
- 支持自定義事件
其實自定義的滾動條,四個方向都能作,只是多謝兩個dom而已。
demo和源碼github
思路
dom部分很簡單:一個外層wrap容器包裹內容,在寫兩個滾動條,只要內容的寬高超過wrap寫死的尺寸,就會出現滾動條了:segmentfault

有三個關鍵的數字須要計算:dom
- 滾動條的width(height)
- 正文的scrollLeft(scrollTop)
- 滾動條的偏移量style.left(top)
以橫向爲例:函數
- 橫向滾動條的width = (正文可視區clientWidth / 正文真實寬度scrollWidth) * 100 + '%'.

- 正文的向左滾動的距離(scrollLeft的差值):
比例關係: scrollLeft / scrollWidth(正文真實寬度) = deltaX(鼠標滑動的距離) / clientWidth(可視區寬度)
因此:scrollLeft的差值 = deltaX / clientWidth * scrollWidth
- 滾動條的偏移量,也就是滾動條應該移動的距離:(scrollLeft / scrollWidth) * 100 + '%'.
scrollLeft 就是上面算出的差值這幾個關係弄清後這玩意基本就算作出來了。ui
須要注意的是,涉及到的事件較多,大概有這麼幾個:this

我把事件函數都保存的實例屬性上了,爲了更方便的管理this和移除事件監聽,總的代碼量只有300行,但寫起來細節仍是挺多的。spa