【问题标题】:Autoplay youtube video on hover/mouseover在悬停/鼠标悬停时自动播放 youtube 视频
【发布时间】:2016-10-15 14:09:57
【问题描述】:

我正在尝试播放 youtube 视频以在 iframe 标记处于焦点时自动播放。尝试了以下但它不工作。我的 jquery 出错了? 我想将 &autoplay=1 添加到 iframe 的 src 中,当它是焦点时。

HTML :-

<div class="vid-wrapper" >
    <iframe width="100%" height="100%" id="video1" src="https://www.youtube.com/embed/bxgorUGjCIw?rel=0" frameborder="0" allowfullscreen scrolling="auto" ></iframe>
</div>

CSS :-

.vid-wrapper{
width: 100%;
position: relative;
padding-bottom: 56.25%;
height: 0;
z-index:-20;
}
.vid-wrapper video, .vid-wrapper iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index:-1;
}

jQuery :-

$(document).ready(function() {
 $("#video1").mouseenter(function(){

  $(this).attr("src",$(this).attr("src") + "&amp;autoplay=1");
 });

$("#video1").mouseleave(function(){
  var src= $(this).attr("src");
  var arr_str = src.split("&amp;");
  $(this).attr("src",arr_str[0]);
  });
});

有什么帮助吗?提前致谢。

【问题讨论】:

    标签: jquery


    【解决方案1】:

    实际上,您并不是真的想更改 src 属性,而是使用 youtube's api

    由于跨域问题(特别是在 stackoverflow 中),sn-p 将工作,但代码可以工作。

    var player;
    function onYouTubeIframeAPIReady() {
      player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'M4Xrh8OP1Jk'
      });
    }
    
    $(document).on('mouseover', '#player', function() {
      player.playVideo();
    });
    $(document).on('mouseout', '#player', function() {
      player.pauseVideo();
    });
    <script src="//www.youtube.com/player_api"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="player"></div>

    这是一个有效的 jsfiddle:
    https://jsfiddle.net/rurc8rb9/

    【讨论】:

    • 它不工作。视频见carbonfiberco.com。它是全屏嵌入
    • 它正在工作。 https: 在上面的代码中缺少 google youtube api
    • 我将上面的代码应用到网站上,但它不起作用!
    • 请看carbonfiberco.com You Tube视频就在首页页脚上方。
    • 1.您的 jQuery 有问题(请注意控制台中的 Uncaught TypeError: $ is not a function 错误)。您可以使用jQuery 而不是$。它将解决这个问题。 2. 我在你的 html 中没有看到任何带有id=#video1 的元素,所以你在youtube2.js 中的代码不会做任何事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2016-06-03
    • 2023-04-05
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多