音量控制js

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</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 class="all">
	<p>當前位置0%</p>
	<div class="bar">
		<div class="box"></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 || 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>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章