0

我開發了純javaScript中的音量控制器。鼠標移動工作正常,但不幸的是我無法使它成爲一個完美的音量控制器。 上有功能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(); 
         } 
        } 
    } 
    

演示http://codepen.io/anon/pen/kpcvJ

回答

1
  1. 由於要執行的功能onmousemove只會在單擊後移動鼠標時纔會執行,因此音量不會因鼠標點擊而發生變化。

  2. 您應該設置onmousemovenullonmouseup

這裏是固定的版本:

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