简体   繁体   中英

javascript conflict between onmousedown and onmousemove

I have developed a volume controller in pure javaScript. mouse move works fine but unfortunately I am unable to make it a perfect volume controller. There are two issues facing on the function

  1. Volume not changing on mouse click
  2. onmousemove function keep on working even after 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(); } } } 

Demo http://codepen.io/anon/pen/kpcvJ

  1. Volume is not changing on mouse click, because the function to be executed onmousemove will only get executed when you move the mouse after clicking.

  2. You should set onmousemove to null inside onmouseup

Here's the fixed version:

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;
    }
}

Updated Demo: http://codepen.io/anon/pen/iHaBe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM