我在纯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();
}
}
}
答案 0 :(得分:1)
鼠标单击时音量不会改变,因为只有在单击后移动鼠标才会执行要执行的功能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;
}
}