【问题标题】:responsive iframe src param based on parent container size基于父容器大小的响应式 iframe src 参数
【发布时间】:2013-02-26 01:41:39
【问题描述】:

我正在开发一个响应式页面,其中包含嵌入的视频内容。

如何根据父容器的宽度更新 iframe src 中的参数 width/height 以及 iframe 属性 width/height 以及窗口/方向变化时的变化?

我的标记:

<div class="content">
    <div class="video">
    <iframe src="http://www.foo.com/embeddedPlayer?id=4062930&width=672&height=377&autoPlay=false" width="672" height="377" border="0" frameborder="0" scrolling="no"></iframe>
    </div>
</div>

这是我的 JS:

var articleBodyWidth = $('.content').width(),
    videoUrl = $('.video'),    
    videoSrc = videoUrl.find('iframe').attr('src'),
    iframeWidth = videoUrl.find('iframe').attr('width'),
    iframeHeight = videoUrl.find('iframe').attr('height');

// function to get param in url
function getParam(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(videoSrc);
  if(results == null) {
    return "";
  } else {
    return results[1];
  }
}

var newWidth = articleBodyWidth,
    newHeight = Math.round( (iframeHeight / iframeWidth) * articleBodyWidth );

// update iframe width and height
videoUrl.find('iframe').attr({
   width: newWidth,
   height: newHeight
});

【问题讨论】:

  • 用代码更新了我的问题。
  • @calebo 找到我的更新答案,是否解决问题

标签: javascript jquery iframe autoresize window-resize


【解决方案1】:

我认为应该这样做

$('.video iframe').attr('src', 'http://www.foo.com/embeddedPlayer?id=4062930&width=' + newWidth+ ' &height='  + newHeight + ' &autoPlay=false').css({
   width: newWidth,
   height: newHeight
})

另一种解决方案是使用正则表达式替换src中的高度和宽度

function updateVideo() {
    var src = $('.video iframe').attr('src');
    src = src.replace(/&width=\d+&/, '&width=' + newWidth + '&');
    src = src.replace(/&height=\d+&/, '&height=' + newHeight + '&');
    $('.video iframe').attr('src', src).attr({
       width: newWidth,
       height: newHeight
    });
}

$(window).on('resize', updateVideo)

【讨论】:

  • 我的窗口调整大小/设备方向改变时是否可以更新这些值?
  • 你需要使用$(window).on('resize', function(){})事件处理
【解决方案2】:

您需要做的是使用 CSS 控制大小。

&lt;iframe src="http://www.foo.com/embeddedPlayer?id=4062930&amp;width=672&amp;height=377&amp;autoPlay=false" border="0" frameborder="0" scrolling="no" id="video"&gt;&lt;/iframe&gt;

<style type="text/css">
#video { width:100%; height:auto: }
</style>

我从 &lt;iframe&gt; 中删除了宽度和高度,以便 CSS 可以接管。

【讨论】:

  • 不幸的是我不能这样做,因为我收到的 iframe url 必须解析参数。
【解决方案3】:

@kcdwayne 是对的。您应该在响应式页面中控制 CSS。 对于嵌入式视频,唯一的变量是“高度”,但如果您使用@media-queries,您可以根据布局更改为不同的屏幕尺寸设置高度。

我会尝试这样做: http://tinyurl.com/a2cxfe6

更多关于嵌入式 Flash 对象的信息在这里: http://www.aleosoft.com/flashtutorial_autofit.html

【讨论】:

  • 我无法控制 flash 对象的高度/宽度,页面生成的宽度和高度基于 url 参数。
猜你喜欢
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 2018-10-06
相关资源
最近更新 更多