2015-09-04 56 views
0

我想在鼠標懸停在它上面播放電影。就像Facebook一樣。Angularjs + HTML在鼠標上播放youtube

<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構建的。 (IM相當新,所以請儘可能也解釋了該解決方案不僅粘貼代碼)

回答

1

加強在這plunker

的解決方案「喜歡」 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); 
    } 
}) 

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

現在我有一個完全的控制:

現在當YT API好了,我可以創建一個播放器與玩家對象$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上運行startPlayer()。當我離開div時,我在ytplayer上運行pausePlayer()

embed-responsive類是inline-block包裹玩家

...而這幾乎是所有。

如果您只需在mouseenter上啓動播放器,Michelem的解決方案可能是最好的選擇和最簡單的選擇。但是如果你需要對玩家更多的控制,請記住我的解決方案(即使它有點棘手)。

希望它有幫助。

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