点击HTML5视频播放的海报图片?

时间:2011-03-11 20:56:52

标签: jquery html5 video

我有一个带海报属性的HTML5视频。我想以某种方式设置它,以便您可以点击视频元素上的任何位置(海报图像的区域),它将触发播放事件并启动视频?我觉得这是相当标准的做法,但我没有办法在没有闪光灯的情况下做到这一点。任何帮助将不胜感激。

7 个答案:

答案 0 :(得分:63)

这对我来说是安德鲁。

在你的html头中添加一小段js:

var video = document.getElementById('video');
video.addEventListener('click',function(){
    video.play();
},false);

或者,只需将onlick属性直接添加到您的html元素:

<video src="your_video" width="250" height="50" poster="your_image" onclick="this.play();"/>

答案 1 :(得分:16)

也发布了此here,但这也适用于此话题。

我有无数问题这样做,但最终提出了一个有效的解决方案。

基本上下面的代码是为视频添加点击处理程序,但忽略了下半部分的所有点击(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();
    }
});

答案 2 :(得分:6)

使用poster属性不会改变行为。它只是在加载视频时显示图像。让视频自动启动(如果浏览器实现不这样做),那么你必须做类似的事情:

<video id="video" ...></video>

在javascript中使用jquery:

$('#video').click(function(){
   document.getElementById('video').play();
});

希望有所帮助

答案 3 :(得分:4)

是的,这听起来像浏览器创建者或html规范编写者只是“忘记”的常规功能。

我写了几个解决方案,但没有一个是真正的跨浏览器或100%可靠。包括点击视频控件的问题会导致停止视频的意外后果。相反,我建议您使用经过验证的解决方案,例如VideoJS:http://videojs.com/

答案 4 :(得分:0)

使用get(0)也可以

    var play = $('.playbutton');
    var video = $('#video');
    play.click(function(){
        video.get(0).play();
    })

答案 5 :(得分:0)

我正在做反应和es6。这是我在阅读Daniel Golden的解决方案后制作的现代版本:

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>
  )
}

答案 6 :(得分:-1)

<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>
相关问题