无需使用按钮即可自动启动模态视频

时间:2015-10-22 12:29:51

标签: javascript jquery html twitter-bootstrap modal-dialog

我创建了一个模态,可以在页面加载时显示youtube视频。问题是我不想用按钮触发这个模态,我只是希望它在页面加载时显示并自动播放这个视频。 我做了一些东西,但是当模态出现时,视频没有出现......

HTML:

<a href="#" class="btn btn-default" data-toggle="modal" data-target="#videoModal" data-theVideo="https://www.youtube.com/embed/g9-66737t1c"></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">&times;</button>
                <div>
                    <iframe width="100%" height="350" src=""></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

JS:

$('#videoModal').modal('show');

autoPlayYouTubeModal();

function autoPlayYouTubeModal() {
  var theModal = $('#videoModal').data("target"),
      videoSRC = $('#videoModal').attr("data-theVideo"),
      videoSRCauto = videoSRC + "?autoplay=1";
  $(theModal + ' iframe').attr('src', videoSRCauto);
  $(theModal + ' button.close').click(function () {
      $(theModal + ' iframe').attr('src', videoSRC);
  });
  $('.modal').click(function () {
      $(theModal + ' iframe').attr('src', videoSRC);
  });
}

https://jsfiddle.net/r4n49db4/

1 个答案:

答案 0 :(得分:0)

通过将https://www.youtube.com/embed/g9-66737t1c添加到iframe src属性

来解决此问题