我已经尝试了这里发布的关于其他问题和 stackexchange 的一些建议,但没有一个令我满意。
我正在尝试将动态内容加载到模式中。特别是 iFrame 中的 YouTube 视频或 Soundcloud 音频。这样任何访问该站点的用户都可以输入视频或音频链接。然后模态动态加载用户链接。每个后续用户都可以看到彼此的链接,所有这些都在一个模态中。 (为每个用户单独加载模式)
我无法让它正常工作。我创建了一个名为“modal.html”的单独 html 文件来对此进行测试,其中包括一个带有适当 YouTube/Soundcloud 剪辑的 iframe。
我也很困惑我是否需要在我的标签中使用“data-remote=”,或者 href 是否足够?或者我是否在第一个模态中使用数据远程。或者两者兼而有之?两者都没有用。
这是我的代码:
<a data-toggle="modal" href="modal.html" data-target="#myModal">Click me</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" data- remote="modal.html" 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>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
最佳答案
为什么都不是 data-remote
或 href
在 youtube 等远程站点上工作
Twitter Bootstrap 的模式使用 AJAX 通过 data-remote
加载远程内容/href
. AJAX 受 same origin policy 约束所以访问不同来源的网站,比如 youtube,会产生这个错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource
所以 data-remote
都不是或 href
会做你想做的。
JSON: 如果您正在获取 json 数据,那么您可能会使用 JSONP .但是由于您需要来自像 youtube 这样的网站的 html,而不是 json,我们需要另一种方法:
解决方案使用 <iFrame>
安<iframe>
将适用于 youtube 和许多其他远程站点(即使此 solition 也不适用于所有站点,因为某些站点,如 Facebook,通过将 X-Frame-Options' 设置为 'DENY' 来明确阻止 iframe)。
将 iframe 用于动态内容的一种方法是:
1) 在模态框正文中添加一个空的 iframe:
<div class="modal-body">
<iframe frameborder="0"></iframe>
</div>
2) 添加一些在单击模态对话框按钮时触发的 jquery。以下代码需要一个 data-src
中的链接目标属性和按钮有一个类 modalButton
.您还可以选择指定 data-width
和 data-height
- 否则它们分别默认为 400 和 300(当然您可以轻松更改它们)。
然后在 <iframe>
上设置属性这会导致 iframe 加载指定页面。
$('a.modalButton').on('click', function(e) {
var src = $(this).attr('data-src');
var height = $(this).attr('data-height') || 300;
var width = $(this).attr('data-width') || 400;
$("#myModal iframe").attr({'src':src,
'height': height,
'width': width});
});
3) 将类和属性添加到模态对话框的 anchor 标记中:
<a class="modalButton" data-toggle="modal" data-src="http://www.youtube.com/embed/Oc8sWN_jNF4?rel=0&wmode=transparent&fs=0" data-height=320 data-width=450 data-target="#myModal">Click me</a>
关于javascript - 使用 bootstrap 3.0 模态加载 iframe 中的动态远程内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20073618/