62

YouTubeiframeを使用して自分のサイトに動画を埋め込みます。

<iframe width="100%" height="443" class="yvideo" id="p1QgNF6J1h0"
              src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
              frameborder="0" allowfullscreen>
</iframe>

そして、私は同じページに複数のビデオを持っています。

javascriptなどを使ってボタンをクリックするだけで全部または1つを止めたい。

出来ますか?

アップデート:

Talvi Watiaが言って使用したことを試しました:

$('#myStopClickButton').click(function(){
  $('.yvideo').each(function(){
    $(this).stopVideo();
  });
});

私が得ている:

Uncaught TypeError: Object [object Object] has no method 'stopVideo' 
4

15 に答える 15

104

残念ながら、これらのAPIは非常に速く進化します。2015年5月の時点で、プレーヤーオブジェクトにメソッドがないため、提案されたソリューションは機能しなくなりましたstopVideo

信頼できる解決策はこのページ(1)にあり、以下で機能します。

<iframe id="youtube_player" class="yt_player_iframe" width="640" height="360" src="http://www.youtube.com/embed/aHUBlv5_K8Y?enablejsapi=1&version=3&playerapiid=ytplayer"  allowfullscreen="true" allowscriptaccess="always" frameborder="0"></iframe>

および次のJS/jQueryコード:

$('.yt_player_iframe').each(function(){
  this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});
于 2015-05-20T18:47:53.073 に答える
38

誰かがまだ答えを探しているなら、私はそれを次のように解決しました:

$("#photos").on("hide",function(){
    var leg=$('.videoPlayer').attr("src");
    $('.videoPlayer').attr("src",leg);
});

ここで、#photosはモーダルのIDであり、.videoPlayerはiframeのクラスです。基本的に、src属性を更新します(そしてビデオの再生を停止します)。それで、

    $('#myStopClickButton').click(function(){
      $('.yvideo').each(function(){
        var el_src = $(this).attr("src");
        $(this).attr("src",el_src);
      });
    });

トリックを行う必要があります。

于 2016-03-30T15:20:46.510 に答える
19

YoutubeJavaScriptAPIリファレンスドキュメントを確認することをお勧めします。

ページに動画を埋め込むときは、次のパラメータを渡す必要があります。

http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1

[すべての動画を停止]ボタンが必要な場合は、動画をループして停止するJavaScriptルーチンを設定できます。

player.stopVideo()

これには、ページ上の各動画のすべてのページIDを追跡することが含まれます。さらに簡単なのは、クラスを作成してからjQuery.eachを使用することです。

$('#myStopClickButton').click(function(){
  $('.myVideoClass').each(function(){
    $(this).stopVideo();
  });
});
于 2013-03-01T19:15:29.643 に答える
19

これがcodepenです、それは私のために働きました。

YTビデオをiframeに埋め込むための最も簡単な解決策を探していましたが、これがそれだと感じています。

私が必要としていたのは、ビデオをモーダルウィンドウに表示し、閉じたときに再生を停止することでした。

コードは次のとおりです:(from:https ://codepen.io/anon/pen/GBjqQr )

    <div><a href="#" class="play-video">Play Video</a></div>
    <div><a href="#" class="stop-video">Stop Video</a></div>
    <div><a href="#" class="pause-video">Pause Video</a></div>

    <iframe class="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/glEiPXAYE-U?enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>

$('a.play-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});

$('a.stop-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});

$('a.pause-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});

さらに、モーダルウィンドウなど、まだ表示されていないDOMオブジェクトで自動再生する場合は、モーダルを表示するために使用していたビデオを再生するために同じボタンを使用すると、機能しないため、これ:

https://www.youtube.com/embed/EzAGZCPSOfg?autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer

注:?autoplay=1&一時停止が機能し続けることを可能にするために、それが配置される場所と次のプロパティの前の「&」の使用。

于 2018-07-18T16:39:12.457 に答える
16

APIは変化し続けるため、面倒です。この純粋なJavaScriptの方法は私のために働いた:

 <div id="divScope" class="boom-lightbox" style="display: none;">
    <iframe id="ytplayer" width="720" height="405"   src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen>    </iframe>
  </div>  

//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');      
//otherwise set scope as the entire document
//var myScope = document;

//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
    for (var i = 0; i < iframes.length; i++) {
        iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
    }
}
于 2016-04-21T23:42:44.307 に答える
14

Talviの回答は引き続き機能する可能性がありますが、YoutubeJavascriptAPIは非推奨としてマークされています。これで、新しいYoutubeIFrameAPIを使用する必要があります。

ドキュメントには、ビデオの埋め込みを実現するためのいくつかの方法が記載されていますが、目標を達成するために、次のものを含める必要があります。

//load the IFrame Player API code asynchronously
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//will be youtube player references once API is loaded
var players = [];

//gets called once the player API has loaded
function onYouTubeIframeAPIReady() {
    $('.myiframeclass').each(function() {
        var frame = $(this);

        //create each instance using the individual iframe id
        var player = new YT.Player(frame.attr('id'));

        players.push(player);
    });
}

//global stop button click handler
$('#mybutton').click(function(){

    //loop through each Youtube player instance and call stopVideo()
    for (var i in players) {
        var player = players[i];
        player.stopVideo();
    }
});
于 2015-03-23T20:53:04.413 に答える
7

この投稿を単純に過大評価して、OPとヘルパーに答えることはできません。video_idを交換するだけの私の解決策:

<div style="pointer-events: none;">
    <iframe id="myVideo" src="https://www.youtube.com/embed/video_id?rel=0&modestbranding=1&fs=0&controls=0&autoplay=1&showinfo=0&version=3&enablejsapi=1" width="560" height="315" frameborder="0"></iframe> </div>

    <button id="play">PLAY</button>

    <button id="pause">PAUSE</button>


    <script>
        $('#play').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                    '{"event":"command","func":"playVideo","args":""}', 
                    '*'); 
            });
        });

        $('#pause').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                  '{"event":"command","func":"pauseVideo","args":""}',
                  '*'); 
            });
        });
    </script>
于 2017-09-13T10:35:43.517 に答える
6

最も簡単な方法は

var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
于 2017-03-18T15:52:23.523 に答える
4

ビデオが内部にあるTwitterBootstrapモーダル/ポップアップの場合、これは私にとってはうまくいきました:

$('.modal.stop-video-on-close').on('hidden.bs.modal', function(e) {
  $('.video-to-stop', this).each(function() {
    this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div id="vid" class="modal stop-video-on-close"
  tabindex="-1" role="dialog" aria-labelledby="Title">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title">Title</h4>
      </div>
      <div class="modal-body">
       <iframe class="video-to-stop center-block"
        src="https://www.youtube.com/embed/3q4LzDPK6ps?enablejsapi=1&rel=0"
        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
        frameborder="0" allowfullscreen>
       </iframe>
      </div>
      <div class="modal-footer">
        <button class="btn btn-danger waves-effect waves-light"
          data-dismiss="modal" type="button">Close</button>
      </div>
    </div>
  </div>
</div>

<button class="btn btn-success" data-toggle="modal"
 data-target="#vid" type="button">Open video modal</button>

マルコの答えに基づいてenablejsapi=1、ビデオのURLにパラメータを追加する必要があることに注意してください(rel=0最後に関連するビデオを表示しないためだけです)。JSpostMessage機能は、すべての面倒な作業を行うものであり、実際にビデオを停止します。

リクエストの権限が原因でスニペットに動画が表示されない場合がありますが、通常のブラウザでは、2018年11月の時点で機能するはずです。

于 2018-11-20T11:59:38.443 に答える
3

これが純粋なJavaScriptソリューションです。

<iframe 
width="100%" 
height="443" 
class="yvideo" 
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0" 
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>


<script>
document.getElementById("myStopClickButton").addEventListener("click",    function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
   video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}

});

于 2018-10-10T11:44:47.060 に答える
2

モーダルポップアップで埋め込み動画を使用する場合のYouTubeiframeの一時停止/停止方法

 $('#close_one').click(function (e) {
         
         
         let link = document.querySelector('.divclass');// get iframe class 
         let link = document.querySelector('#divid');// get iframe id
         let video_src = link.getAttribute('src');

         $('.youtube-video').children('iframe').attr('src', ''); // set iframe parent div value null 
         $('.youtube-video').children('iframe').attr('src', video_src);// set iframe src again it works perfect

     });
于 2020-09-04T04:52:25.340 に答える
1

タブビューを終了するとき、またはIonicアプリを最小化するときにiframeYouTubeビデオを一時停止または停止する方法も参照してください。

$scope.stopVideo = function() {
 var iframe = document.getElementsByTagName("iframe")[0].contentWindow;
 iframe.postMessage('{"event":"command","func":"'+'stopVideo'+   '","args":""}', '*');
 }
于 2016-02-01T05:14:33.840 に答える
1

$('#aboutVideo .close').on('click',function(){
			var reSrc = $('.aboutPlayer').attr("src");
			$('.aboutPlayer').attr("src",reSrc)
		})
#aboutVideo{
	width: 100%;
	height: 100%;
}
#aboutVideo .modal-dialog, #aboutVideo .modal-dialog .modal-content, #aboutVideo .modal-dialog .modal-content .modal-body{
	width: 100%;
	height: 100%;
	margin: 0 !important;
	padding: 0 !important;
}
#aboutVideo .modal-header{
	padding: 0px; 
	border-bottom: 0px solid #e5e5e5; 
	position: absolute;
	right: 4%;
	top: 4%;
}
#aboutVideo .modal-header .close{
	opacity: 1;
	position: absolute;
	z-index: 99;
	color: #fff;
}
#aboutVideo .modal-header button.close{
      border-radius: 50%;
    width: 7vw;
    height: 7vw;
    position: absolute;
    right: 4%;
    top: 7%;
    background: aliceblue;
}
#aboutVideo .modal-header button.close:hover{
	background-color: rgba(255, 255, 255, 0.28);
}
#aboutVideo .modal-header button.close img{
	width: 20px;
	margin-top: -0.2vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<li class="see-video fa" type="button" data-toggle="modal" data-target="#aboutVideo">
			<label>SEE VIDEO</label>
		</li>
<div class="modal fade" id="aboutVideo" tabindex="-1" role="dialog" aria-labelledby="aboutVideoLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><img src="http://www.freeiconspng.com/uploads/white-close-button-png-16.png"></span></button>
				</div>
				<div class="modal-body">
				<iframe class="aboutPlayer" width="100%" height="100%" src="https://www.youtube.com/embed/fju9ii8YsGs?autoplay=0&showinfo=0&controls=2&rel=0" frameborder="0" allowfullscreen poster="https://www.google.co.in/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwiOvaagmqfWAhUHMY8KHUuJCnkQjRwIBw&url=http%3A%2F%2Fnodeframework.com%2F&psig=AFQjCNEaHveDtZ81veNPSvQDx4IqaE_Tzw&ust=1505565378467268"></iframe>
				</div>
			</div>
		</div>
	</div>

于 2017-09-15T12:41:09.457 に答える
1

これが、更新されたyoutubeAPIを使用した私のソリューションです。開始、停止、一時停止が含まれます。

https://codesandbox.io/s/youtube-video-player-73x4b

于 2022-01-12T11:03:05.200 に答える
0
var vid_element = $('.youtube-player');
vid_element.detach();
$('#parent').append(vid_element);

src属性を再割り当てするよりも、要素を切り離してから追加する方が信頼性が高いことがわかりました。

于 2022-02-20T11:21:43.780 に答える