Bootstrap 3 и Youtube в модальном
Я пытаюсь использовать функцию Modal из Bootstrap 3, чтобы показать мое видео Youtube. Он работает, но я не могу нажимать на какие-либо кнопки в видео Youtube.
Любая помощь по этому поводу?
Здесь мой код:
<div id="link">My video</div>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<iframe width="400" height="300" frameborder="0" allowfullscreen=""></iframe>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.10.1.min.js"><\/script>')</script>
<script src="js/bootstrap.min.js"></script>
<script>
$('#link').click(function () {
var src = 'http://www.youtube.com/v/FSi2fJALDyQ&autoplay=1';
$('#myModal').modal('show');
$('#myModal iframe').attr('src', src);
});
$('#myModal button').click(function () {
$('#myModal iframe').removeAttr('src');
});
</script>
Ответы
Ответ 1
Я нашел эту проблему (или проблему, которую я нашел и описал в https://github.com/twbs/bootstrap/issues/10489), связанную с преобразованием (переводом) CSS3 в классе .modal.fade .modal-dialog
.
В bootstrap.css вы найдете строки, показанные ниже:
.modal.fade .modal-dialog {
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
transform: translate(0, -25%);
-webkit-transition: -webkit-transform 0.3s ease-out;
-moz-transition: -moz-transform 0.3s ease-out;
-o-transition: -o-transform 0.3s ease-out;
transition: transform 0.3s ease-out;
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
transform: translate(0, 0);
}
Замена этих строк следующим образом покажет фильм правильно (в моем случае):
.modal.fade .modal-dialog {
-webkit-transition: -webkit-transform 0.3s ease-out;
-moz-transition: -moz-transform 0.3s ease-out;
-o-transition: -o-transform 0.3s ease-out;
transition: transform 0.3s ease-out;
}
.modal.in .modal-dialog {
}
Ответ 2
Я собрал этот динамический видеоролик html/jQuery для видеороликов script, который автоматически воспроизводит видеоролик YouTube при нажатии кнопки триггера (ссылки), триггер также содержит ссылку для воспроизведения. script найдет собственный загрузочный модальный вызов и откроет общий модальный шаблон с данными из триггера. Смотрите ниже и дайте мне знать, что вы думаете. Мне бы хотелось услышать мысли...
HTML MODAL TRIGGER:
<a href="#" class="btn btn-default" data-toggle="modal" data-target="#videoModal" data-theVideo="http://www.youtube.com/embed/loFtozxZG0s" >VIDEO</a>
HTML MODAL VIDEO TEMPLATE:
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div>
<iframe width="100%" height="350" src=""></iframe>
</div>
</div>
</div>
</div>
</div>
ФУНКЦИЯ ЗАВЕТА:
//FUNCTION TO GET AND AUTO PLAY YOUTUBE VIDEO FROM DATATAG
function autoPlayYouTubeModal(){
var trigger = $("body").find('[data-toggle="modal"]');
trigger.click(function() {
var theModal = $(this).data( "target" ),
videoSRC = $(this).attr( "data-theVideo" ),
videoSRCauto = videoSRC+"?autoplay=1" ;
$(theModal+' iframe').attr('src', videoSRCauto);
$(theModal+' button.close').click(function () {
$(theModal+' iframe').attr('src', videoSRC);
});
});
}
ФУНКЦИОНАЛЬНЫЙ ВЫЗОВ:
$(document).ready(function(){
autoPlayYouTubeModal();
});
FIDDLE:
http://jsfiddle.net/jeremykenedy/h8daS/1/
Ответ 3
У меня есть один совет для вас!
Я бы использовал:
$('#myModal').on('hidden.bs.modal', function () {
$('#myModal iframe').removeAttr('src');
})
вместо:
$('#myModal button').click(function () {
$('#myModal iframe').removeAttr('src');
});
Потому что вы также можете закрыть модальный без кнопки, поэтому там с этим кодом он будет удалять видео каждый раз, когда модальная скроется.
Ответ 4
Обнаружено это в другом потоке, и он отлично работает на рабочем столе и на мобильных устройствах - что не похоже на некоторые другие решения. Добавьте script в конец вашей страницы:
<!--Script stops video from playing when modal is closed-->
<script>
$("#myModal").on('hidden.bs.modal', function (e) {
$("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
});
</script>
Ответ 5
Вот еще одно решение: Настроить видео youtube HTML5
Просто добавьте? html5 = 1 в исходный атрибут iframe, например:
<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>
Ответ 6
Я решил его на шаблоне Wordpress:
$videoLink ="http://www.youtube.com/watch?v=yRuVYkA8i1o;".
<?php
parse_str( parse_url( $videoLink, PHP_URL_QUERY ), $my_array_of_vars );
$youtube_ID = $my_array_of_vars['v'];
?>
<a class="video" data-toggle="modal" data-target="#myModal" rel="<?php echo $youtube_ID;?>">
<img src="<?php bloginfo('template_url');?>/assets/img/play.png" />
</a>
<div class="modal fade video-lightbox" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body"></div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
jQuery(document).ready(function ($) {
var $midlayer = $('.modal-body');
$('#myModal').on('show.bs.modal', function (e) {
var $video = $('a.video');
var vid = $video.attr('rel');
var iframe = '<iframe />';
var url = "//youtube.com/embed/"+vid+"?autoplay=1&autohide=1&modestbranding=1&rel=0&hd=1";
var width_f = '100%';
var height_f = 400;
var frameborder = 0;
jQuery(iframe, {
name: 'videoframe',
id: 'videoframe',
src: url,
width: width_f,
height: height_f,
frameborder: 0,
class: 'youtube-player',
type: 'text/html',
allowfullscreen: true
}).appendTo($midlayer);
});
$('#myModal').on('hide.bs.modal', function (e) {
$('div.modal-body').html('');
});
});
</script>
Ответ 7
Если вы не хотите редактировать загрузочный CSS или все вышеперечисленное не поможет вам вообще (например, в моем случае), есть простое исправление для запуска видео в модальном режиме на Firefox.
Вам просто нужно удалить класс "fade" из модального и, поскольку он также открывает класс "in":
$('#myModal').on('shown.bs.modal', function () {
$('#myModal').removeClass('in');
});
Ответ 8
Bootstrap предоставляет модальные всплывающие функциональные возможности из коробки.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<a class="btn btn-primary" data-toggle="modal" href="#modal-video"><i class="fa fa-play"></i> watch video</a>
<div class="modal fade" id="modal-video" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">close <i class="fa fa-times"></i></button>
</div>
<div class="modal-body">
<iframe type="text/html" width="640" height="360" src="//www.youtube.com/embed/GShZUiyqEH0?rel=0?wmode=transparent&fs=1&rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen=""></iframe>
<p>Your video</p>
</div>
</div>
</div>
</div>
Ответ 9
MMhh... Не могли бы вы разместить весь свой HTML-документ и какой браузер/версию использовать?
Я воссоздал вашу страницу и протестировал ее в трех браузерах (Chrome, FF, IE8). Я смог остановить и запустить потрясающий трейлер WDS4 без каких-либо проблем. Вот мой код:
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="bootstrap.min.css" rel="stylesheet" media="screen">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="../../assets/js/html5shiv.js"></script>
<script src="../../assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="link">My video</div>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<iframe width="400" height="300" frameborder="0" allowfullscreen=""></iframe>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap JavaScript plugins) -->
<script src="jq.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap.min.js"></script>
<script>
$('#link').click(function () {
var src = 'http://www.youtube.com/v/FSi2fJALDyQ&autoplay=1';
$('#myModal').modal('show');
$('#myModal iframe').attr('src', src);
});
$('#myModal button').click(function () {
$('#myModal iframe').removeAttr('src');
});
</script>
</body>
</html>
Вы могли бы попытаться добавить Z-Index вашего модального игрока в стек?
$('#myModal iframe').css("z-index","999");
Ответ 10
<a href="#" class="btn btn-default" id="btnforvideo" data-toggle="modal" data-target="#videoModal">VIDEO</a>
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div>
<iframe width="100%" height="315" src="https://www.youtube.com/embed/myvideocode" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
Ответ 11
используя $('#introVideo').modal('show');
, конфликтует с запуском бутстрапа. Когда вы нажмете на ссылку, которая открывает Modal, она закроется сразу после завершения анимации затухания.
Просто удалите $('#introVideo').modal('show');
(используя bootstrap v3.3.2)
Вот мой код:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<!-- triggering Link -->
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>
<!-- Intro video -->
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item allowfullscreen"></iframe>
</div>
</div>
</div>
</div>
</div>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"> </script>
<script>
//JS
$('#videoLink').click(function () {
var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';
// $('#introVideo').modal('show'); <-- remove this line
$('#introVideo iframe').attr('src', src);
});
$('#introVideo button.close').on('hidden.bs.modal', function () {
$('#introVideo iframe').removeAttr('src');
})
</script>
Ответ 12
user3084135 ответ хорошо работал как основа для меня, но мне также необходимо было включить:
- Тег "видео" для локально размещенного видео, а также тег "iframe" для видео с внешним размещением.
- Убедитесь, что источник удален, но модаль был отклонен.
- Решение работало в ответном дизайне Bootstrap
- Все видео автоматически воспроизводятся в модальном режиме
- Возможны несколько модалов
Мое готовое решение выглядит так:
КНОПКА MODAL TRIGGER
<a href="#" class="portfolio-link" data-toggle="modal" data-frame="iframe" data-target="#portfolioModal1" data-theVideo="http://www.youtube.com/embed/xxxxxxxx">
Атрибут data-frame может быть "iframe" или "video", чтобы отобразить соответствующий тип тега: iframe для внешних видео, видео для локального размещения.
РЕПОНДОВЫЕ ВИДЕОДАТЕЛИ ВОДОПОДГОТОВКИ
плавающий фрейм:
<div align="center" class="embed-responsive embed-responsive-16by9">
<iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>
</div>
видео:
<div align="center" class="embed-responsive embed-responsive-16by9">
<video width="640" height="364" controls>
<source src="" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
Они оба находятся в стандартных ответных модальных divs Bootstrap.
JQUERY SCRIPT
<script>
$(document).ready(function(){
function autoPlayModal(){
var trigger = $("body").find('[data-toggle="modal"]');
trigger.click(function() {
var theFrame = $(this).data( "frame" );
var theModal = $(this).data( "target" );
videoSRC = $(this).attr( "data-theVideo" );
if (theFrame == "iframe") {
videoSRCauto = videoSRC+"?autoplay=1" ;
} else {
videoSRCauto = videoSRC;
$("[id*=portfolioModal] video").attr('autoplay','true');
}
$(theModal+' '+ theFrame).attr('src', videoSRCauto);
$("[id*=portfolioModal]").on('hidden.bs.modal', function () {
$("[id*=portfolioModal] "+ theFrame).removeAttr('src');
})
});
}
autoPlayModal();
});
</script>
Так как autoplay работает по-разному с iframe и видео тегами, условный используется для каждого. Чтобы разрешить несколько модалов, для их идентификации используется подстановочный знак (портфолиоModal1-6 в моем случае).
Ответ 13
У меня была эта же проблема - я только что добавил ссылки на шрифты - awesome cdn - комментируя загрузочный блок ниже, разрешил мою проблему.. действительно не устранил проблему, поскольку шрифт awesome все еще работал -
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
Ответ 14
Ok. Я нашел решение.
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h3 class="modal-title" id="modal-login-label">Capital Get It</h3>
<p>Log in:</p>
</div>
<div class="modal-body">
<h4>Youtube stuff</h4>
<iframe src="//www.youtube.com/embed/lAU0yCDKWb4" allowfullscreen="" frameborder="0" height="315" width="100%"></iframe>
</div>
</div>
</div>
</div>
</div>
Ответ 15
Для Bootstrap 4, который обрабатывает видео, изображения и страницы...
http://jsfiddle.net/c4j5pzua/
$('a[data-modal]').on('click',function(){
var $page = $(this).data('page');
var $image = $(this).data('image');
var $video = $(this).data('video');
var $title = $(this).data('title');
var $size = $(this).data('size');
$('#quickview .modal-title').text($title);
if ($size) { $('#quickview .modal-dialog').addClass('modal-'+$size); }
if ($image) {
$('#quickview .modal-body').html('<div class="text-center"><img class="img-fluid" src="'+$image+'" alt="'+$title+'"></div>');
} else if ($video) {
$('#quickview .modal-body').html('<div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/'+$video+'?autoplay=1" allowfullscreen></iframe></div>');
}
if ($page) {
$('#quickview .modal-body').load($page,function(){
$('#quickview').modal({show:true});
});
} else {
$('#quickview').modal({show:true});
}
$('#quickview').on('hidden.bs.modal', function(){
$('#quickview .modal-title').text('');
$('#quickview .modal-body').html('');
if ($size) { $('#quickview .modal-dialog').removeClass('modal-'+$size); }
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<div class="container my-4">
<h3 class="mb-4">Bootstrap 4 Modal YouTube Videos, Images & Pages</h3>
<a href="javascript:;" class="btn btn-primary" data-modal data-video="zpOULjyy-n8" data-title="Video Title" data-size="xl">Video</a>
<a href="javascript:;" class="btn btn-primary" data-modal data-image="https://v4-alpha.getbootstrap.com/assets/brand/bootstrap-social-logo.png" data-title="Image Title" data-size="">Image</a>
<a href="javascript:;" class="btn btn-primary" data-modal data-page="https://getbootstrap.com" data-title="Page Title" data-size="lg">Page *</a>
<p class="mt-4">* Clicking this will break it, but it'll work using a local page!</p>
</div>
<div class="modal fade" id="quickview" tabindex="-1" role="dialog" aria-labelledby="quickview" aria-hidden="true">
<div class="modal-dialog modal-dialog-scrollable modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
Ответ 16
Попробуйте это для Bootstrap 4
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<h2>Embedding YouTube Videos</h2>
<p>Embedding YouTube videos in modals requires additional JavaScript/jQuery:</p>
<!-- Buttons -->
<div class="btn-group">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/lQAUq_zs-XU">Launch Video 1</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/pvODsb_-mls">Launch Video 2</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/4m3dymGEN5E">Launch Video 3</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#videoModal" data-video="https://www.youtube.com/embed/uyw0VZsO3I0">Launch Video 4</button>
</div>
<!-- Modal -->
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header bg-dark border-dark">
<button type="button" class="close text-white" data-dismiss="modal">×</button>
</div>
<div class="modal-body bg-dark p-0">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
// Set iframe attributes when the show instance method is called
$("#videoModal").on("show.bs.modal", function(event) {
let button = $(event.relatedTarget); // Button that triggered the modal
let url = button.data("video"); // Extract url from data-video attribute
$(this).find("iframe").attr({
src : url,
allow : "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
});
});
// Remove iframe attributes when the modal has finished being hidden from the user
$("#videoModal").on("hidden.bs.modal", function() {
$("#videoModal iframe").removeAttr("src allow");
});
});
</script>
</body>
</html>
посетите: https://parrot-tutorial.com/run_code.php?snippet=bs4_modal_youtube
Ответ 17
$('#videoLink').click(function () {
var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';
// $('#introVideo').modal('show'); <-- remove this line
$('#introVideo iframe').attr('src', src);
});
$('#introVideo button.close').on('hidden.bs.modal', function () {
$('#introVideo iframe').removeAttr('src');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="#" onclick="location.href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css'; return false;" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!-- triggering Link -->
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>
<!-- Intro video -->
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item allowfullscreen"></iframe>
</div>
</div>
</div>
</div>
</div>