当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 原生js+css调节音量滑块

原生js+css调节音量滑块

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了js调节音量滑块的具体代码,供大家参考,具体内容如下

效果

html部分

<body>
<div class="all">
<p>当前位置0%</p>
<div class="bar">
<div class="box"></div>
</div>
</div>
</body>

css部分

<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>

js逻辑

<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 || window.event //兼容性
let mousex = e.clientx //鼠标按下的位置
window.onmousemove = function (ev) {
let e = ev || window.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 //取消默认事件
}
window.onmouseup = function () {
window.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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网