0

我用纯 JavaScript 开发了一个音量控制器。鼠标移动工作正常,但不幸的是我无法使其成为完美的音量控制器。该功能面临两个问题:

  1. 鼠标点击音量不变

  2. 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

4

1 回答 1

1
  1. 单击鼠标时音量不会改变,因为要执行的功能onmousemove只有在单击后移动鼠标时才会执行。

  2. 你应该设置onmousemovenull里面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

于 2014-05-24T19:36:51.673 回答