我在视频元素中添加了一个事件监听器,以便用户可以通过单击元素上的任意位置来播放或暂停视频.我注意到即使我点击视频控件(例如更改音量滑块),事件也会触发,这显然不是我的意图.
这有一个相对简单的解决方法吗?
最佳答案
您可以使用接受事件参数的函数处理视频元素的onclick事件.此事件参数将填充大量有关鼠标单击的数据,包括其在图层中的X / Y位置(应该是视频标记)
原文链接:https://www.f2er.com/js/429755.html只有当点击位于视频的某些区域时,您才可以触发播放/暂停事件.我在下面列举了一个示例,我们处理视频中的所有点击,除了底部50像素.
document.getElementById("videoElement").onclick = function(ev){
var vid = document.getElementById("videoElement");
var heightOfControls = 50;
// You'll have to figure out a good height to use for your unclickable region where the controls are.
// I used 50 pixels as an example.
var areaAboveControls = vid.height - heightOfControls;
// the layerY attribute of the event lets us know where the mouse was within the topmost layer when the click occurred.
// Using this we can find out where we are in the video and react accordingly.
// Remember that 0 is at the top of the screen on the Y axis,so we need to use greater than to find out if it's BELOW
// our area above the controls.
if(ev.layerY > areaAboveControls)
{
alert("Clicked controls!");
}
else
{
alert("Did not click controls");
// Raise play/pause event from here since the controls won't handle the event and we can safely toggle play/pause.
}
};
通过一些实验,您应该能够为heightOfControls找到一个很好的值,它可以为您提供所需的行为.
小提琴:http://jsfiddle.net/hTYck/4/
希望这可以帮助!