首頁  >  文章  >  web前端  >  js如何實現調整音量滑桿

js如何實現調整音量滑桿

王林
王林轉載
2020-03-17 11:11:432856瀏覽

js如何實現調整音量滑桿

首先,我們來看看效果:

js如何實現調整音量滑桿

(推薦教學:javascript教學

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(&#39;box&#39;)[0]
var bar = document.getElementsByClassName(&#39;bar&#39;)[0]
var all = document.getElementsByClassName(&#39;all&#39;)[0]
var p = document.getElementsByTagName(&#39;p&#39;)[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 + &#39;px&#39;
// 计算比例
let bili = newL / cha * 100
p.innerHTML = &#39;当前位置&#39; + Math.ceil(bili) + &#39;%&#39;
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 + &#39;px&#39;
let bili = left / cha * 100
p.innerHTML = &#39;当前位置&#39; + Math.ceil(bili) + &#39;%&#39;
console.log(left)
return false
}
</script>

更多酷炫javascript特效程式碼,盡在:javascript特效

以上是js如何實現調整音量滑桿的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jb51.net。如有侵權,請聯絡admin@php.cn刪除