这篇文章主要介绍js如何实现水平和竖直滑动条,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
首先来看水平滑动条,效果图如下:
代码如下:
<html> <head> <meta charset="UTF-8"> <title>水平滑动条</title> <style> * { margin: 0; padding: 0; } .scroll { margin: 100px; width: 500px; height: 5px; background: #ccc; position: relative; } .bar { width: 10px; height: 20px; background: #369; position: absolute; top: -7px; left: 0; cursor: pointer; } p{ margin-left: 100px; } </style> </head> <body> <div class="scroll" id="scroll"> <div class="bar" id="bar"> </div> </div> <p></p> <script> //获取元素 var scroll = document.getElementById('scroll'); var bar = document.getElementById('bar'); var ptxt = document.getElementsByTagName('p')[0]; bar.onmousedown = function(event) { var event = event || window.event; //页面事件的X减去当前相对于最近的祖先定位元素 var x = event.clientX - this.offsetLeft; document.onmousemove = function(event) { var event = event || window.event; var left = event.clientX - x; if (left < 0) left = 0; else if (left > scroll.offsetWidth - bar.offsetWidth) { left = scroll.offsetWidth - bar.offsetWidth; } //改变滑块的left bar.style.left = left + "px"; ptxt.innerHTML = "当前滑块的移动的百分比:" + parseInt(left / (scroll.offsetWidth - bar.offsetWidth) * 100) + "%"; //防止选择内容 window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } } //当鼠标弹起的时候,不做任何操作 document.onmouseup = function() { document.onmousemove = null; } </script> </body> </html>
竖直滑动条效果图如下:
代码如下:
<html> <head> <meta charset="UTF-8"> <title>竖直滑动条</title> <style> * { margin: 0; padding: 0; } .scroll{ margin: 100px; width: 5px; height: 320px; background: #ccc; position: relative; } .bar { width: 15px; height: 5px; background: #369; position: absolute; top: 0px; left: -5; cursor: pointer; } p{ margin-left: 100px; } </style> </head> <body> <div class="scroll" id="scroll"> <div class="bar" id="bar"> </div> </div> <p></p> <script> //获取元素 var scroll = document.getElementById("scroll"); var bar = document.getElementById("bar"); var ptxt = document.getElementsByTagName('p')[0]; //添加事件 bar.onmousedown = function(event) { var event = event || window.event; //页面事件的Y减去当前相对于最近的祖先定位元素 var y = event.clientY - this.offsetTop; // 拖动需要写到down里面 document.onmousemove = function(event) { var event = event || window.event; //获取移动的距离 var top = event.clientY - y; if (top < 0){ top = 0; } else if (top > scroll.offsetHeight - bar.offsetHeight){ top = scroll.offsetHeight - bar.offsetHeight; } //改变滑块的top bar.style.top = top + "px"; //按照百分比得到当前滑动的距离 ptxt.innerHTML = "当前滑块的移动的百分比:" + parseInt(top/(scroll.offsetHeight - bar.offsetHeight) * 100) + "%"; //防止选择内容 window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } } //当鼠标弹起的时候,不做任何操作 document.onmouseup = function() { document.onmousemove = null; } </script> </body> </html>
这里之所以加入移动百分比的展示效果,主要是考虑到后续如果需要对接后台的数据就可以达到动态控制的目的。
以上是“js如何实现水平和竖直滑动条”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。