【问题标题】:Is there a way to get the "width" and "height" of an "<iframe>" at the backend?有没有办法在后端获取“<iframe>”的“宽度”和“高度”?
【发布时间】:2011-05-04 06:36:06
【问题描述】:

我正在为图像嵌入服务编写后端。我们正在考虑使用类似于 YouTube 的 iframe 来支持嵌入。

例如:

<iframe type="text/html" src="http://example.com/photos/embed/abc/" width="640px" height="480px" frameborder="1"> </iframe>

在任何地方使用上面的 iframe 都应该将图像嵌入到 iframe 中(以及一些额外的东西,如标题等)。但是,我想返回与 iframe 中指定的“宽度”和“高度”大小相同的图像。我想图像大小调整应该在后端进行才能正常工作。

在这种情况下,我需要 iframe 的宽度和高度才能在后端访问。有没有办法在后端解决这个问题?例如,这些是 HTTP 请求的一部分还是类似的任何东西?

PS:我在后端使用 Django(如果有帮助的话)

【问题讨论】:

    标签: html django iframe


    【解决方案1】:

    在您的示例中,页面/脚本 [http://example.com/photos/embed/abc/] 无法获得宽度/高度的值。 但是您可以在 URL 中传递宽度/高度变量,例如

    &lt;iframe type="text/html" src="http://example.com/photos/embed/abc/?width=640&amp;height=480" width="640px" height="480px" frameborder="1"&gt; &lt;/iframe&gt;

    【讨论】:

    • 谢谢,是的,我已经考虑过这种方法。唯一的问题是,如果用户在 URL 和 iframe 属性中指定不同的值,这可能会导致图像大小和 iframe 大小不同步。有什么方法可以解决这个问题?
    • 如果你坚持使用iframe,那恐怕是与/abc/页面沟通的唯一方式。
    【解决方案2】:

    不,iframe 的大小在后端不可用。

    当您在 iframe 中显示页面而不是直接显示图像时,该页面可以使用客户端脚本来获取 iframe 的大小,并在图像标记中的 URL 中发送该信息。

    类似:

    window.onload = function(){
      var b = document.body;
      if (window.opera) b = b.parentNode;
      var img = document.createElement('img');
      img.src = 'http://example.com/photos/embed/abc/?w=' + b.clientWidth + '&h=' + b.clientHeight;
      img.alt = '';
      document.body.appendChild(img);
    }
    

    您可能在页面中也需要这种样式,以便 body 元素占据 iframe 的整个高度:

    html,body { height: 100%; }
    

    【讨论】:

    • 谢谢,这似乎是最好的方法。
    【解决方案3】:

    您可以使用 javascript(演示在 jquery 中以便于跨浏览器实现)来检查 iframe 元素并将其大小属性复制到 iframe 请求的 url:以下将通过延迟 url 来满足您的需要在确定宽度和高度之前设置 iframe。

    <script type="text/javascript">
    
    $(document).ready(function() {
      var frame = $('#myiframeid');
      var width = frame.attr('width');
      var height = frame.attr('height');
      var url = 'http://example.com/photos/embed/abc/?w=' + width + '&h=' + height;
    
      frame.attr('src', url);
    });
    
    </script>
    
    <iframe id="myiframeid" type="text/html" src="myemptyblankpage.html" width="640px" height="480px" frameborder="1"> </iframe>
    

    希望对您有所帮助。

    【讨论】:

    • 这也是一个不错的方法,但我觉得这对于用户来说嵌入的代码太多了。只给用户“
    猜你喜欢
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多