我已经用纯javaScript开发了一个音量控制器。鼠标移动效果很好,但是很遗憾,我无法使其成为完美的音量控制器。
该功能面临两个问题
鼠标单击时音量未更改onmousemove
功能即使在onmouseup
之后仍可继续工作
var vControl = document.getElementById("voumecontrol");
var vNow = document.getElementById("volumenow");
var resultDiv = document.getElementById("result");
vControl.onmousedown = function (e) {
vControl.onmousemove = function (e) {
var varPosition = e.pageY - vControl.offsetTop;
var volPercentage = varPosition / vControl.offsetHeight;
kili = Math.abs((e.pageY - (vControl.offsetTop + vControl.offsetHeight)) / vControl.offsetHeight);
var volumePer = kili * 100;
vNow.style.height = volumePer + "%";
resultDiv.innerHTML = "volume position " + volumePer + "%";
}
vControl.onmouseup = function (e) {
vControl.onmousemove = function (e) {
e.preventDefault();
}
}
}
演示http://codepen.io/anon/pen/kpcvJ
最佳答案
单击鼠标时音量不会改变,因为要执行的功能onmousemove
仅在单击鼠标后移动鼠标时才会执行。
您应该在onmousemove
内将null
设置为onmouseup
这是固定版本:
var vControl = document.getElementById("voumecontrol");
var vNow = document.getElementById("volumenow");
var resultDiv = document.getElementById("result");
var mousemovemethod = function (e) {
var varPosition = e.pageY - vControl.offsetTop;
var volPercentage = varPosition / vControl.offsetHeight;
kili = Math.abs((e.pageY - (vControl.offsetTop + vControl.offsetHeight)) / vControl.offsetHeight);
var volumePer = kili * 100;
vNow.style.height = volumePer + "%";
resultDiv.innerHTML = "volume position " + volumePer + "%";
}
vControl.onmousedown = function (e) {
mousemovemethod(e);
vControl.onmousemove = mousemovemethod;
vControl.onmouseup = function (e) {
vControl.onmousemove = null;
}
}
更新的演示:http://codepen.io/anon/pen/iHaBe