温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

用js实现调节音量滑块的方法

发布时间:2020-03-26 14:07:36 来源:亿速云 阅读:1108 作者:小新 栏目:web开发

今天小编分享的是用js实现调节音量滑块的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

用js实现调节音量滑块的方法

首先,我们来看一下效果:

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

关于用js实现调节音量滑块的方法就分享到这里了,当然并不止以上和大家分析的办法,不过小编可以保证其准确性是绝对没问题的。希望以上内容可以对大家有一定的参考价值,可以学以致用。如果喜欢本篇文章,不妨把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI