Angularjs + HTML 在鼠标悬停时播放 youtube

Angularjs + HTML play youtube on mouse over

我想在鼠标悬停在电影上时播放电影。就像脸书一样。

<div class="col-sm-12">   
  <div class="embed-responsive embed-responsive-16by9">   
    <iframe class="embed-responsive-item" src="//www.youtube.com/embed/pQIXz-uhjIk">
    </iframe>   
  </div>
</div>

该网站是用 angularjs 和 html 构建的。 (我很新所以如果可能的话也请解释解决方案而不仅仅是粘贴代码)

Br

这可能是您可以尝试的解决方案:

JSFiddle

HTML:

<div ng-app="myApp" ng-controller="dummy">
    <div class="col-sm-12">
        <div class="embed-responsive embed-responsive-16by9">
            <div ng-hide="url" ng-mouseenter="url = 'http:////www.youtube.com/embed/pQIXz-uhjIk?autoplay=1'">OVERME</div>
            <iframe ng-show="url" class="embed-responsive-item" ng-src="{{trustSrc(url)}}"></iframe>
        </div>
    </div>
</div>

JS:

angular.module('myApp', [])
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {

    $scope.trustSrc = function (src) {
        return $sce.trustAsResourceUrl(src);
    }
}]);

在此 plunker

中构建解决方案 "like" facebook

要动态 运行 播放器,您必须集成 ifram api。

您必须将此添加到您的 index.html

<script src="https://www.youtube.com/iframe_api"></script>

然后你需要像这样在你的控制器中处理他们 API 的异步加载(不知道他们为什么这样做):

//i create a promise to wait for the YT.loaded to be true
var defered = $q.defer();
var promise = defered.promise;

//i launch this function until the YT.loaded is true
var interval = $interval(function(){
  if(YT.loaded){
    //if the YT api is loaded, i cancel the interval and resolve the promise
    defered.resolve();
    $interval.cancel(interval);
  }
})

现在我可以在 YT api 准备就绪时创建播放器:

var videoId = "pQIXz-uhjIk";
//when the API is ready
promise.then(function(){
  //i create an Iframe player in the div with the "ytplayer" id
  $scope.ytplayer = new YT.Player('ytplayer', {
      height: '200',
      width: '300', 
      videoId: videoId
    }) ; 
}); 

现在我可以使用 $scope.ytplayer 对象完全控制播放器。

我准备了两个函数来启动和暂停播放器:

$scope.startPlayer = function(player){
  player.playVideo();
};
$scope.pausePlayer = function(player){
  player.pauseVideo();
}

现在让我们看看 HTML 和鼠标技巧:

  <div ng-show="ytplayer" ng-mouseenter="startPlayer(ytplayer)" ng-mouseleave="pausePlayer(ytplayer)" class="embed-responsive embed-responsive-16by9">
     <div id="ytplayer"></div>
  </div>

只有在设置了 ytplayer 时,我才会显示我的 div。当我在播放器 ytplayer 上输入 div 我 运行 startPlayer() 时。当我离开 div 我 运行 pausePlayer()ytplayer.

embed-responsiveclass是一个inline-block来包裹播放器

...这就是全部了。

如果您只需在鼠标输入上启动播放器,Michelem 的解决方案可能是最佳选择和最简单的选择。但如果您需要对播放器进行更多控制,请记住我的解决方案(即使它有点棘手)。

希望对您有所帮助。