禁用父单击,但保持子单击事件处于活动状态



我希望下面的代码中的按钮具有单击事件,而不是父div。

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<div id="myVideo">
<video controls="" autoplay="" name="media">
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
<button id="myButton">Play Video</button>
</div>
</body>
</html>

我尝试使用 css 指针事件,但如果父级有它,那么子按钮不起作用。

像这样添加 onclick 事件处理程序:<button id="myButton" onclick="function(e) {e.stopPropagation();}">Play Video</button>

event.stopPropagation 停止将单击事件传播到父元素。在此处了解更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

var myVideo = document.getElementById("myVideo"); 
function playPause()
{ 
if (myVideo.paused) 
myVideo.play(); 
else 
myVideo.pause(); 
}
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<div id="mydIV">
<video ID="myVideo" controls="" autoplay="" name="media">
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
<button onclick="playPause()">Play/Pause</button> 
</div>
</body>
</html>

这将帮助您
快乐编码....

我相信这就是你要找的:

<div id="myVideo">
<video name="media" id="video">
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
</div>
<button id="myButton" onclick="document.getElementById('video').play()">Play Video</button>

您至少有两个选择。 首先是检查事件是由按钮还是div 触发的。 或者防止事件在 DOM 树上冒泡。在jQuery中,你可以通过调用方法"stopPropagation()"来做到这一点。

这里有一个类似问题的答案。

最新更新