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

时间:2015-09-04 07:15:53

标签: html angularjs youtube

一旦鼠标悬停在电影上,我想播放一部电影。就像facebook一样。

<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构建。 (我很新,所以请尽可能解释解决方案,而不仅仅是粘贴代码)

2 个答案:

答案 0 :(得分:1)

这可以是您可以使用的解决方案:

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);
    }
}]);

答案 1 :(得分:1)

在此plunker

中建立一个“喜欢”facebook的解决方案

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

您必须将其添加到index.html

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

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

//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。当我输入div时,我在播放器startPlayer()上运行ytplayer。当我离开div时,我在pausePlayer()上运行ytplayer

embed-responsive类是一个inline-block来包装播放器

......这就是全部。

如果你只需要在mouseenter上启动播放器,Michelem的解决方案可能是最好的选择和最简单的选择。但如果你需要更多控制玩家,请记住我的解决方案(即使它有点棘手)。

希望它有所帮助。

相关问题