单击图像即可启动/播放嵌入式 (iframe) youtube 视频

发布于 2024-11-14 02:36:50 字数 476 浏览 2 评论 0原文

我正在尝试通过单击图像来开始播放嵌入式 YouTube 视频。这个想法是在视频上方放置一个图像,当单击该图像时,它会淡出并开始播放视频。

我正在使用 jquery 淡化图像,并希望找到一种使用 jquery 播放或单击视频的方法。

淡入淡出效果很好,但我不知道如何触发视频播放。 我通过将视频设置为自动播放并隐藏它,然后在单击图像时淡入视频,让它在几个浏览器上工作。在大多数浏览器上,视频在淡入时会自动播放,但在 Chrome 中,即使隐藏时它也会开始自动播放。它在 iOS 中也运行得不好。

由于我对此很陌生,我什至不确定我写的是否100%正确,但我尝试过类似的方法但没有成功:

     $('#IMAGE').click(function() { $('#VIDEO').play(); });

那么,我将如何让视频在图片点击? 有没有办法只使用 jquery 在单击图像时播放视频?

先感谢您。

I'm trying to start playing an embedded youtube video by clicking an image. The idea is to have an image on top of a video, and when the image is clicked it fades out and starts playing the video.

I'm using jquery to fade the image, and was hoping to find a way to play or click the video using jquery as well.

The fading is working fine, but I can't figure out how to trigger the video to play.
I got it to work on a couple of browsers by setting the video to autoplay and hide it, and then fade in the video when the image was clicked. On most browsers the video would autoplay when faded in, but in chrome it started to autoplay even when it was hidden. It didn't work well in iOS either.

Since I'm pretty new at this, I'm not even sure if I'm writing it 100% correct, but I've tried something like this without success:

     $('#IMAGE').click(function() { $('#VIDEO').play(); });

So, how would I go about to make the video play on an image click?
Is there a way to play the video when the image is clicked, just using jquery?

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

假情假意假温柔 2024-11-21 02:36:50

快速而肮脏的方法是简单地将 iframe 替换为使用 jQuery 设置了 autoplay=1 的框架。

HTML

占位符:

<div id="videoContainer">
  <iframe width="450" height="283" src="https://www.youtube.com/embed/VIDEO_ID_HERE?wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>
</div>

自动播放链接:

<a class="introVid" href="#video">Watch the video</a></p>

JQUERY

调用函数的 onClick 捕获器

jQuery('a.introVid').click(function(){
  autoPlayVideo('VIDEO_ID_HERE','450','283');
});

函数

/*--------------------------------
  Swap video with autoplay video
---------------------------------*/

function autoPlayVideo(vcode, width, height){
  "use strict";
  $("#videoContainer").html('<iframe width="'+width+'" height="'+height+'" src="https://www.youtube.com/embed/'+vcode+'?autoplay=1&loop=1&rel=0&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>');
}

The quick and dirty way is to simply swap out the iframe with one that has autoplay=1 set using jQuery.

THE HTML

Placeholder:

<div id="videoContainer">
  <iframe width="450" height="283" src="https://www.youtube.com/embed/VIDEO_ID_HERE?wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>
</div>

Autoplay link:

<a class="introVid" href="#video">Watch the video</a></p>

THE JQUERY

The onClick catcher that calls the function

jQuery('a.introVid').click(function(){
  autoPlayVideo('VIDEO_ID_HERE','450','283');
});

The function

/*--------------------------------
  Swap video with autoplay video
---------------------------------*/

function autoPlayVideo(vcode, width, height){
  "use strict";
  $("#videoContainer").html('<iframe width="'+width+'" height="'+height+'" src="https://www.youtube.com/embed/'+vcode+'?autoplay=1&loop=1&rel=0&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>');
}
执手闯天涯 2024-11-21 02:36:50

您可以像这样简单地执行此操作

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

,其中 image_id 是您单击的图像 id,some_id 是 div 的 id,其中 iframe 也可以直接使用 iframe id。

You can do this simply like this

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.

守望孤独 2024-11-21 02:36:50

启动视频

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

停止视频

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

您可能需要将“&autoplay=1”替换为“?autoplay=1”,以防没有其他参数

适用于 FF 和 YouTube 上的 vimeo 和 youtube。铬合金

To start video

var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);

To stop video

var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);

You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters

works for both vimeo and youtube on FF & Chrome

看海 2024-11-21 02:36:50

youtube iframe 示例

<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>

点击播放 HTML 元素

<div class="videoplay">Play</div> 

用于播放视频的 jQuery 代码

$('.videoplay').on('click', function() {
    $("#video")[0].src += "?autoplay=1";
});

感谢 https://codepen.io/马丁沃尔夫/笔/dyLAC

Example youtube iframe

<iframe id="video" src="https://www.youtube.com/embed/xNM7jEHgzg4" frameborder="0"></iframe>

The click to play HTML element

<div class="videoplay">Play</div> 

jQuery code to play the Video

$('.videoplay').on('click', function() {
    $("#video")[0].src += "?autoplay=1";
});

Thanks to https://codepen.io/martinwolf/pen/dyLAC

残龙傲雪 2024-11-21 02:36:50

您应该能够指定一个可以安全编写脚本的域。 api文档提到
“作为额外的安全措施,您还应该在 URL 中包含 origin 参数”
http://code.google.com/apis/youtube/iframe_api_reference.html
src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com"
将是你的 iframe 的 src 。

然而它并没有很好的记录。我现在正在尝试类似的事情。

You are supposed to be able to specify a domain that is safe for scripting. the api document mentions
"As an extra security measure, you should also include the origin parameter to the URL"
http://code.google.com/apis/youtube/iframe_api_reference.html
src="http://www.youtube.com/embed/J---aiyznGQ?enablejsapi=1&origin=mydomain.com"
would be the src of your iframe.

however it is not very well documented. I am trying something similar right now.

夏夜暖风 2024-11-21 02:36:50

Html 代码:-

<a href="#" id="playerID">Play</a>
<iframe src="https://www.youtube.com/embed/videoID" class="embed-responsive-item" data-play="0" id="VdoID" ></iframe>

Jquery 代码:-

$('#playerID').click(function(){
    var videoURL = $('#VdoID').attr('src'),
    dataplay = $('#VdoID').attr('data-play');

    //for check autoplay
    //if not set autoplay=1
    if(dataplay == 0 ){
        $('#VdoID').attr('src',videoURL+'?autoplay=1');
        $('#VdoID').attr('data-play',1);
     }
     else{
        var videoURL = $('#VdoID').attr('src');
        videoURL = videoURL.replace("?autoplay=1", "");
        $('#VdoID').prop('src','');
        $('#VdoID').prop('src',videoURL);

        $('#VdoID').attr('data-play',0);
     }

});

就是这样!

Html Code:-

<a href="#" id="playerID">Play</a>
<iframe src="https://www.youtube.com/embed/videoID" class="embed-responsive-item" data-play="0" id="VdoID" ></iframe>

Jquery Code:-

$('#playerID').click(function(){
    var videoURL = $('#VdoID').attr('src'),
    dataplay = $('#VdoID').attr('data-play');

    //for check autoplay
    //if not set autoplay=1
    if(dataplay == 0 ){
        $('#VdoID').attr('src',videoURL+'?autoplay=1');
        $('#VdoID').attr('data-play',1);
     }
     else{
        var videoURL = $('#VdoID').attr('src');
        videoURL = videoURL.replace("?autoplay=1", "");
        $('#VdoID').prop('src','');
        $('#VdoID').prop('src',videoURL);

        $('#VdoID').attr('data-play',0);
     }

});

Thats It!

半﹌身腐败 2024-11-21 02:36:50

您可以使用这个。
图像将位于视​​频 div 的顶部。如果您单击图像,则会出现视频并开始播放。
这也适用于桌面设备和响应式设备。在视频 URL 末尾添加 ?autoplay=1 不会在移动设备上自动播放视频。
但这个解决方案适用于所有设备。
注意:在 stackoverflow 中运行代码后,这可能不起作用,但在本地或生产站点上可以正常工作。

var $ = window.jQuery;
      $('.custom-svg-container').click(function (ev) {
            $(`<div id="custom-youtube-video"></div>
            <script> 
                var tag = document.createElement('script');
                tag.src = "https://www.youtube.com/player_api";
                var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                var player;

                function onPlayerReady(event) {
                    event.target.mute();
                    event.target.playVideo();
                }

                function onYouTubePlayerAPIReady() {
                    var id = 'i810CxN5Q6Q';
                    player = new YT.Player('custom-youtube-video', {
                        width: "560",
                        height: "349",
                        videoId: id,
                        playerVars: {
                            // 'playsinline': 1,
                            // 'autoplay': 1,
                            // 'mute': 1,
                            // 'controls': 0,
                            // "playlist": id,
                            // 'loop': 1
                        },
                        events: {
                            'onReady': onPlayerReady,
                        }
                    });
                }

            <\/script>`).appendTo($('.custom-iframe-container'))

            setTimeout(function() {
                $('.custom-benefit-image').addClass('showVideo')
            }, 10)
            // $('#custom-youtube-video')[0].src.includes("?autoplay=1&mute=1") ? "" : $('#custom-youtube-video')[0].src+= "?autoplay=1&mute=1";
            // ev.preventDefault();
        });
div.taskboard-container { 
        margin: auto;
        border: solid; 
        border-radius: 18px;
        border-width: 15px; 
        background: #000000; 
    }
                        
    .custom-iframe-container { 
        display: none;
        position: relative; 
        width: 100%; 
        padding-bottom: 65%;
        height: 0; 
        justify-content: center; 
        align-items: center;
        border: solid; 
        border-radius: 18px;
        border-width: 15px;
        background: #000000;
    }

    .custom-benefit-image.showVideo .custom-iframe-container { 
        display: flex;
    }

    .custom-benefit-image.showVideo .custom-svg-container { 
        display: none 
    }

    .custom-benefit-image.showVideo .taskboard-container { 
        display: none 
    }
                        
    .custom-benefit-image .custom-svg-container { 
        position: absolute; 
        height: 100%; 
        width: 100%; 
        display: flex; 
        justify-content: center;
        align-items: center; 
        z-index: 9999;
        cursor: pointer; 
    }
                        
    .custom-benefit-image .custom-svg-div {
        width: 12%;
        height: auto;
    }

    .custom-iframe-container iframe{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }
<html>
  <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
<body>
  <!-- 1. The <iframe> (video player) will replace this <div> tag. -->
  <div class='custom-benefit-image' style="height: 700px; width: 700px; position: relative;">
      <div class='custom-svg-container'>
          <div class='custom-svg-div'>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
              "><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm115.7 272l-176 101c-15.8 8.8-35.7-2.5-35.7-21V152c0-18.4 19.8-29.8 35.7-21l176 107c16.4 9.2 16.4 32.9 0 42z"></path></svg>
          </div>
      </div>

      <div class='custom-iframe-container'> 
        
      </div>   

      <div class='taskboard-container' style="height: 700px; width: 700px;"> 
          <img width="100%" height="100%" src='https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510__480.jpg' > 
      </div> 
  </div>

</body>
</html>

You can work with this one.
The image will be on top of the video div. If you click on the image then the video will appear and will start playing.
This works on desktop and also responsive devices also. Adding ?autoplay=1 at the end of the video URL does not auto play the video on the mobile device.
But this solution work on every devices.
Note: This may not work after running the code in stackoverflow but works fine on local or production site.

var $ = window.jQuery;
      $('.custom-svg-container').click(function (ev) {
            $(`<div id="custom-youtube-video"></div>
            <script> 
                var tag = document.createElement('script');
                tag.src = "https://www.youtube.com/player_api";
                var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
                var player;

                function onPlayerReady(event) {
                    event.target.mute();
                    event.target.playVideo();
                }

                function onYouTubePlayerAPIReady() {
                    var id = 'i810CxN5Q6Q';
                    player = new YT.Player('custom-youtube-video', {
                        width: "560",
                        height: "349",
                        videoId: id,
                        playerVars: {
                            // 'playsinline': 1,
                            // 'autoplay': 1,
                            // 'mute': 1,
                            // 'controls': 0,
                            // "playlist": id,
                            // 'loop': 1
                        },
                        events: {
                            'onReady': onPlayerReady,
                        }
                    });
                }

            <\/script>`).appendTo($('.custom-iframe-container'))

            setTimeout(function() {
                $('.custom-benefit-image').addClass('showVideo')
            }, 10)
            // $('#custom-youtube-video')[0].src.includes("?autoplay=1&mute=1") ? "" : $('#custom-youtube-video')[0].src+= "?autoplay=1&mute=1";
            // ev.preventDefault();
        });
div.taskboard-container { 
        margin: auto;
        border: solid; 
        border-radius: 18px;
        border-width: 15px; 
        background: #000000; 
    }
                        
    .custom-iframe-container { 
        display: none;
        position: relative; 
        width: 100%; 
        padding-bottom: 65%;
        height: 0; 
        justify-content: center; 
        align-items: center;
        border: solid; 
        border-radius: 18px;
        border-width: 15px;
        background: #000000;
    }

    .custom-benefit-image.showVideo .custom-iframe-container { 
        display: flex;
    }

    .custom-benefit-image.showVideo .custom-svg-container { 
        display: none 
    }

    .custom-benefit-image.showVideo .taskboard-container { 
        display: none 
    }
                        
    .custom-benefit-image .custom-svg-container { 
        position: absolute; 
        height: 100%; 
        width: 100%; 
        display: flex; 
        justify-content: center;
        align-items: center; 
        z-index: 9999;
        cursor: pointer; 
    }
                        
    .custom-benefit-image .custom-svg-div {
        width: 12%;
        height: auto;
    }

    .custom-iframe-container iframe{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }
<html>
  <head>
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
<body>
  <!-- 1. The <iframe> (video player) will replace this <div> tag. -->
  <div class='custom-benefit-image' style="height: 700px; width: 700px; position: relative;">
      <div class='custom-svg-container'>
          <div class='custom-svg-div'>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
              "><!-- Font Awesome Pro 5.15.4 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) --><path d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm115.7 272l-176 101c-15.8 8.8-35.7-2.5-35.7-21V152c0-18.4 19.8-29.8 35.7-21l176 107c16.4 9.2 16.4 32.9 0 42z"></path></svg>
          </div>
      </div>

      <div class='custom-iframe-container'> 
        
      </div>   

      <div class='taskboard-container' style="height: 700px; width: 700px;"> 
          <img width="100%" height="100%" src='https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510__480.jpg' > 
      </div> 
  </div>

</body>
</html>

心作怪 2024-11-21 02:36:50

这应该可以完美运行,只需复制这个 div 代码

<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&hl=en_US&autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>

This should work perfect just copy this div code

<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&hl=en_US&autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文