您的位置:首页技术文章
文章详情页

js实现自定义滚动条的示例

浏览:70日期:2024-04-14 11:22:33

自定义滚动条

目录

代码实例 代码解析 下载源码链接

代码实例

* {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='https://www.haobala.com/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实现自定义滚动条的资料请关注好吧啦网其它相关文章!

标签: JavaScript
相关文章: