Play youtube video on hover

↘锁芯ラ 提交于 2020-02-05 02:32:34

问题


I just need to play the youtube video only when hovered

I have here a fiddle and can't get it to work.

$(document).ready(function(){
  $(function() {

      var playersrc = jQuery(iframe).attr('src');

          $('div').hover(function(){
          $('iframe').attr('src',playersrc+'&autoplay=1');
      }, function(){
          $('iframe').attr('src',playersrc);
      });
  });       
});

https://jsfiddle.net/rhr5p0pg/2/

updated fiddle: https://jsfiddle.net/rhr5p0pg/4/

now it plays all and when your mouse leaves the it does not go back to its originial video


回答1:


You store just the first video uri (src).

What about something like this

$(document).ready(function(){
  var nowPlaying = "none";
      $('div').hover(function(){
          nowPlaying = $(this).find('iframe').attr('src');
          $(this).find('iframe').attr('src',nowPlaying+'&autoplay=1');
      }, function(){
          $(this).find('iframe').attr('src',nowPlaying);
      });

});

https://jsfiddle.net/rhr5p0pg/5/




回答2:


You need to add the video using Iframe Youtube Api, follow the examples here.

Initialize your player and the use this Jquery code:

//Hover play
$('iframe').on('mouseover',function(){
    player.playVideo();
});

//Blur Pause

$('iframe').on('mouseout',function(){
    player.playVideo();
});



回答3:


It is easier to use the Youtube video API. With the API you have more controle over the videos.

https://developers.google.com/youtube/iframe_api_reference




回答4:


If someone has the issue that on hover doesn't play it's because of the Autoplay policy was changed. You need to set mute to your video. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes



来源:https://stackoverflow.com/questions/47302076/play-youtube-video-on-hover

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!