本篇文章给大家分享使用 JavaScript 实现调节音量滑块的代码实例. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
首先, 我们来看一下效果:
下面来看看代码:
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="UTF-">
- <title>
- JS 调节音量滑块
- </title>
- <style>
- .all { width: 500px; height: 80px; margin: 100px auto; position: relative;
- } .bar { width: 500px; height: 20px; border-radius: 10px; background: #aaa;
- position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto;
- cursor: pointer; } .box { width: 30px; height: 30px; background: #000;
- position: absolute; bottom: 0; top: 0; margin: auto 0; border-radius: 50%;
- cursor: pointer; transition: left 0.1s linear 0s; }
- </style>
- </head>
- <body>
- <div>
- <p>
- 当前位置 0%
- </p>
- <div>
- <div>
- </div>
- </div>
- </div>
- <script>
- var box = document.getElementsByClassName('box')[0]
- var bar = document.getElementsByClassName('bar')[0]
- var all = document.getElementsByClassName('all')[0]
- var p = document.getElementsByTagName('p')[0]
- var cha = bar.offsetWidth - box.offsetWidth box.onmousedown = function(ev) {
- let boxL = box.offsetLeft let e = ev || Windows.event // 兼容性
- let mouseX = e.clientX // 鼠标按下的位置
- Windows.onmousemove = function(ev) {
- let e = ev || Windows.event let moveL = e.clientX - mouseX // 鼠标移动的距离
- let newL = boxL + moveL //left 值
- // 判断最大值和最小值
- if (newL < 0) {
- newL = 0
- }
- if (newL >= cha) {
- newL = cha
- }
- // 改变 left 值
- box.style.left = newL + 'px'
- // 计算比例
- let bili = newL / cha * 100 p.innerHTML = '当前位置' + Math.ceil(bili) + '%'
- return false // 取消默认事件
- }
- Windows.onmouseup = function() {
- Windows.onmousemove = false // 解绑移动事件
- return false
- }
- return false
- };
- // 点击音量条
- bar.onclick = function(ev) {
- let left = ev.clientX - all.offsetLeft - box.offsetWidth / 2
- if (left < 0) {
- left = 0
- }
- if (left >= cha) {
- left = cha
- }
- box.style.left = left + 'px'let bili = left / cha * 100 p.innerHTML = '当前位置' + Math.ceil(bili) + '%'console.log(left) return false
- }
- </script>
- </body>
- </HTML>
更多 web 前端 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/web/javascript/17512.html