首页 > 解决方案 > 自动播放无法在移动设备上运行 YouTube 视频

问题描述

该视频无法在移动设备上自动播放,我知道该问题已被多次询问,但该代码是专门为我的网站开发的(由一位回答我更多的开发人员)。所以我不能完全改变它,我能告诉我要添加什么让它工作吗?

<script>
var player;

function onYouTubePlayerAPIReady() {
  player = new YT.Player('player', {
    playerVars: {
      'autoplay': 1,
      'controls': 0,
      'autohide': 1,
      'wmode': 'opaque',
      'showinfo': 0,
      'loop': 1,
      'mute': 1,
      //'start': 15,
      //'end': 110,
      'playlist': '{{ product.metafields.left_image.left_image[forloop.index0] }}'
    },
    videoId: '{{ product.metafields.left_image.left_image[forloop.index0] }}',
    events: {
      'onReady': onPlayerReady
    }
  });

}

function onPlayerReady(event) {
  event.target.mute();
  $('#text').fadeIn(400);
  //why this? Well, if you want to overlay text on top of your video, you
  //will have to fade it in once your video has loaded in order for this
  //to work in Safari, or your will get an origin error.
}

//this pauses the video when it's out of view, just wrap your video in .m-//video
$(window).scroll(function() {
  var hT = $('.m-video').height(),
      wS = $(this).scrollTop();
  if (wS > hT) {
    player.pauseVideo();
  }
  else {
    player.playVideo();
  }
});

</script>

标签: htmlmobileyoutubefancyboxoverlay

解决方案


您可以在onPlayerReady函数末尾添加以下代码:

if(window.innerWidth < 768) {
  player.playVideo();
}

此代码将通过检查屏幕尺寸开始在移动设备上播放视频。


推荐阅读