js實現自定義滾動條的示例
自定義滾動條
目錄
代碼實例 代碼解析 下載源碼鏈接代碼實例
* {padding: 0;margin: 0;}#box1 {width: 500px;height: 20px;background: #999;position: relative;margin: 20px auto;}#box2 {width: 20px;height: 20px;background: green;position: absolute;}#box3 {width: 0;height: 0;margin: 20px auto;}#box3 img {width: 100%;height: 100%;}<div id='box1'><div id='box2'></div></div><div id='box3'><img src='http://www.cgvv.com.cn/bcjs/1.jpg'></div>// 獲取dom元素var oBox1 = document.getElementById(’box1’);var oBox2 = document.getElementById(’box2’);var oBox3 = document.getElementById(’box3’);// 按下滾動條后的操作oBox2.onmousedown = function(e) {// 獲取事件的必備操作,保證事件被獲取var oEvent = e || event// 保證只有被按下滾動條后才能執行此函數document.onmousemove = function(e) {var oEvent = e || eventvar l = oEvent.clientX - oBox1.offsetLeft// 獲取滾動條可活動的寬度范圍var wid = oBox1.offsetWidth - oBox2.offsetWidthif (l < 0) {l = 0} else if (l > wid) {l = wid}// 位置定位oBox2.style.left = l + ’px’// 根據滾動條位置獲得比例var scale = l / wid// 圖片的寬度和高度var w = 3264 * scalevar h = 4080 * scale// oBox3.style.cssText是加在內嵌style中的oBox3.style.cssText += ’width:’ + w + ’px;height:’ + h + ’px;’}// 保證鼠標松開后事件不再執行document.onmouseup = function() {document.onmousemove = nulldocument.onmousedown = null}}
代碼解析
elem.style.cssText是加在內嵌style中的
// oBox3.style.cssText是加在內嵌style中的oBox3.style.cssText += ’width:’ + w + ’px;height:’ + h + ’px;
下載源碼鏈接
星輝的Github
以上就是js實現自定義滾動條的示例的詳細內容,更多關于js實現自定義滾動條的資料請關注好吧啦網其它相關文章!
相關文章:
