我有一个带有poster属性的HTML5视频。 我想以某种方式设置它,使您可以单击视频元素上的任何位置(海报图像区域),并触发播放事件并开始播放视频? 我觉得这是相当标准的做法,但是我找不到一种方法来实现这一点而不使用flash。 任何帮助都将不胜感激。
这对我很有效,Andrew。
在您的html头部添加此小段js:
var video = document.getElementById('video');
video.addEventListener('click',function(){
video.play();
},false);
或者,直接在你的HTML元素上添加一个onclick属性:
<video src="your_video" width="250" height="50" poster="your_image" onclick="this.play();"/>
我也在这里发布了,但是这个解决方案同样适用于这个讨论。
我曾经遇到过无数问题,但最终找到了一个可行的解决方案。
基本上下面的代码为视频添加了一个点击处理程序,但忽略了下部的所有点击(0.82是任意的值,但似乎适用于所有大小)。
$("video").click(function(e){
// handle click if not Firefox (Firefox supports this feature natively)
if (typeof InstallTrigger === 'undefined') {
// get click position
var clickY = (e.pageY - $(this).offset().top);
var height = parseFloat( $(this).height() );
// avoids interference with controls
if (clickY > 0.82*height) return;
// toggles play / pause
this.paused ? this.play() : this.pause();
}
});
使用poster属性不会改变行为,它只是在加载视频时显示图像。如果想让视频自动开始播放(如果浏览器实现没有这样做),则需要执行以下操作:
<video id="video" ...></video>
使用jQuery的JavaScript代码:
$('#video').click(function(){
document.getElementById('video').play();
});
是的,这听起来像是浏览器创建者或html规范编写者“遗漏”的常规功能。
我已经写了几个解决方案,但它们都不是真正的跨浏览器或100%稳定的。包括点击视频控件时出现的问题会产生意想不到的后果,导致视频停止播放。相反,我建议您使用像VideoJS这样的经过验证的解决方案:http://videojs.com/
const Video = ({videoSources, poster}) => {
return (
<video
controls
poster={poster}
onClick={({target: video}) => video.paused ? video.play() : video.pause()}
>
{_.map(videoSources, ({url, type}, i) =>
<source key={i} src={url} type={type} />
)}
</video>
)
}
使用 get(0) 也可以正常工作
var play = $('.playbutton');
var video = $('#video');
play.click(function(){
video.get(0).play();
})
你可以不使用 jQuery
或其他任何东西来完成。只需使用纯粹的 JavaScript:
var video = document.getElementById('yourVideoId');
document.onmousedown = function(e) {
if (event.button == 0){
video.paused ? video.play() : video.pause();
}
}
<script type="text/javascript">
function actualNextSibling(el) { // needed to smooth out default firefox/IE behavior
do { el = el.nextSibling } while (el && el.nodeType !== 1);
return el;
}
</script>
<div onclick="actualNextSibling(this).style.display='block'; this.style.display='none'">
<img src="splash.jpg" alt="splash" style="cursor: pointer" />
</div>
<div style="display: none">
<iframe width="440" height="248" src="//www.youtube.com/embed/9FOZEbEpyA8?rel=0&autoplay=1"frameborder="0" allowfullscreen></iframe>
</div>
onclick="this.play();"
改为onclick="this.paused?this.play():this.pause();"
。灵感来自于https://dev59.com/W2Ml5IYBdhLWcg3wiXZ7#20434695。 - Daniel Goldenonclick="if (typeof InstallTrigger == 'undefined') (this.paused ? this.play() : this.pause());"
它在 Mac 版的 FireFox、Safari 和 Chrome 上运行良好。还未在 Windows 上进行测试。 - Dan Berlyoungreturn false;
添加到防止默认行为的代码中,解决了@patrick提到的问题。但是,请注意,使用此解决方案时,双击将不会触发全屏播放。 - Alex