在音乐播放器中,音量和进度都是以进度条的形式显示和设置,所以进度条的拖拽效果还是比较重要的。一下以音量条部分为例:
html和css部分
<div id="volume">
<div id="setVolume">
<div id="setVolumeBtn"></div>
</div>
</div>
#volume {
width: 100px;
height: 3px;
background-color: #e0e0e0;
margin: 10px 0;
}
#setVolume {
width: 30%;
height: 100%;
background-color: #D2413A;
position: relative;
}
#setVolumeBtn {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #D2413A;
position: absolute;
right: -4px;
top: -2px;
cursor: pointer;
display: none;
}
js部分
var totalVolume = document.getElementById("volume");
var volume = document.getElementById("setVolume");
var setVolumeBtn = document.getElementById("setVolumeBtn");
//拖动设置音量
setVolumeBtn.onmousedown = function (event) {
var e = event || window.event;
document.onmousemove = function () {
changeVolume();
};
};
//拖动后弹起鼠标不做任何操作
document.onmouseup = function () {
document.onmousemove = null;
};
//点击音量条跳至相应音量
totalVolume.onclick = function () {
changeVolume();
};
//鼠标进入音量条时出现按钮
totalVolume.onmouseover = function () {
setVolumeBtn.style.display = "block";
};
//鼠标离开音量条时按钮消失
totalVolume.onmouseout = function () {
setVolumeBtn.style.display = "none";
};
//音量改变
function changeVolume(event) {
var e = event || window.event;
var volumeWidth = 0;
volumeWidth = e.clientX - totalVolume.offsetLeft;
if (volumeWidth < 0) {
volumeWidth = 0;
} else if (volumeWidth > totalVolume.offsetWidth) {
volumeWidth = totalVolume.offsetWidth;
}
volume.style.width = volumeWidth + "px";
setVolume();
}
//音量-宽度转换
function setVolume() {
var theTotalWidth = totalVolume.offsetWidth;
var theWidth = volume.offsetWidth;
audio.volume = theWidth / theTotalWidth;
}