jQuery - Tab with videos… how do I get videos to stop playing when I switch between tabs?

余生长醉 提交于 2019-12-21 02:53:18

问题


I am new to jQuery, and I managed to create a tab interface. I want each section of my tab to have a YouTube video. However, when I click play on the video that is on tab 1 for example, and then switch to tab 2, the video on tab 1 still keeps on playing. Please see the entire code here:

http://jsfiddle.net/WwfFE/3/

I would greatly appreciate any help on how to stop the video once the user clicks on other tabs.

Also, when I run this on my Android, flash enabled phone, the videos don't seem to play. Any idea of what I need to do to fix? Or do I need to fix anything else to make code browser compatible?


回答1:


This should work:

http://jsfiddle.net/WwfFE/5/

I simply put all your URL's in an array. When the user decides to leave the tab, I clear the src of the iframe so that the video "stops" playing.

The first time your currentTab variable is still empty though, so I retrieve it by looking at which <li> has its class set to active. From this <li> I take the link and set the currentTab variable to its href.

if (currentTab == '') {
   //Find current tab:
   currentTab = $('#tabs ul li.active').find('a').attr('href');
}

//Stop playing video:
if (currentTab != '')
   $('div#' + currentTab).find('iframe').attr('src', '');

When he gets back to any tab, you should not forget to set the src back though, else your iFrame will be empty. It's what I do here:

var index = $(this).attr('id');
$('div#' + currentTab).find('iframe').attr('src', urls[index]);

This code can still be optimized though to reduce the flickering. An easy way to do this is by setting a function on the load trigger of the iframe's. This way you know when the video has been successfully set and it is then that you want to show the tab to the user.




回答2:


Without using any special targeting of iframe or video ids, here's how I stop any playing movie when selecting a different tab. Uses the native bootstrap tab events:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var iframe = $(e.relatedTarget.hash).find('iframe'); 
    var src = iframe.attr('src');
    iframe.attr('src', '');
    iframe.attr('src', src);
s});


来源:https://stackoverflow.com/questions/8731947/jquery-tab-with-videos-how-do-i-get-videos-to-stop-playing-when-i-switch-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!