onmousedown和onmousemove之间的javascript冲突

时间:2014-05-24 18:55:52

标签: javascript javascript-events mouseevent onmousedown onmousemove

我在纯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();
            }
        }
    }
    
  3. 演示http://codepen.io/anon/pen/kpcvJ

1 个答案:

答案 0 :(得分:1)

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

  2. 您应该将onmousemove设置为null内的onmouseup

  3. 这是固定版本:

    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