javascript MouseWheel event & video volume - preve

2019-09-01 09:34发布

I'm trying to control a video volume using the MouseWheel,
I want to completely disable the page scroll when my mouse is over the video,
it works but there's a problem when the video's volume reaches the min & max levels:
the page scroll begins...and I don't want the page scroll if my mouse is over the video!
Actually I'm trying it in chrome:

var popo = document.getElementById('popo');
var coco = document.getElementById('coco');
//popo.play();

//setTimeout(function(){
//    popo.pause();
//},3000);

var current = 0;
var doScroll = function (e) {
    // cross-browser wheel delta
    e = window.event || e;
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));

    // Do something with `delta`
    current = current + delta;
    coco.innerHTML = current;

    if(delta== 1){popo.volume+=0.1;}
    if(delta== -1){popo.volume-=0.1;}

    e.preventDefault();
};

if (popo.addEventListener) {
   popo.addEventListener("mousewheel", doScroll, false);
    popo.addEventListener("DOMMouseScroll", doScroll, false);
} else {
    popo.attachEvent("onmousewheel", doScroll);
}

JSFiddle DEMO: http://jsfiddle.net/NSjqd/5/

2条回答
放荡不羁爱自由
2楼-- · 2019-09-01 10:18

If you check the console, the video is throwing an exception when trying to set a volume over the 1.0 value, and it doesn't reach the e.preventDefault()

A try/catch around where you set the volume would fix it.

try {
  if(delta== 1){popo.volume+=0.1;}
  if(delta== -1){popo.volume-=0.1;}
} catch(e) {}
查看更多
淡お忘
3楼-- · 2019-09-01 10:19

You will want to add a condition to your if statement to turn it up or down like so:

if(delta== 1 && popo.volume <= 0.9){popo.volume+=0.1;}
if(delta== -1 && popo.volume > 0.1){popo.volume-=0.1;}

DEMO

查看更多
登录 后发表回答