【问题标题】:Scaling an iFrame depending on window size and content size根据窗口大小和内容大小缩放 iFrame
【发布时间】:2022-10-24 19:00:03
【问题描述】:

我的页面上有一个动态生成的 iFrame,它使用变量对象加载网站。

这一切都很好理解。我现在面临的挑战是,在某些情况下,比如我在移动设备上查看,框架宽度超过了我的移动设备宽度。

// STATIC VALUE
let screenSize = {
    "height": window.innerHeight,
    "width" window.innerWidth:
}
// DYNAMICALLY GENERATED VARIABLE
let frameValue = {
    "url": "https://example.com",
    "height": 913,
    "width": 1600
}

//Using this variable, the iframe property is set as follows using javascript
$('#dynamicFrame').attr('src', frameValue.url);
$('#dynamicFrame').width(frameValue.width);
$('#dynamicFrame').height(frameValue.height);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- HTML DYNAMIC iFRAME -->
<iframe src="" id="dynamicFrame" frameBorder="0" width="100%" height="100%" scrolling="auto"> </iframe>

需要: 我想要一种算法(或者可能是一些代码)来缩放或缩放 iframe,同时保持其纵横比。

这意味着我希望在考虑 frameValue.width 和 frameValue.height 时将 frameValue.url (example.com) 的内容加载到 iframe 中。

笔记: 我不介意 iframe 看起来更小或边缘有暗带,就像您在移动设备上观看视频或在移动设备上使用缩放或 Microsoft 团队,而共享屏幕的人在桌面设备上一样。

如果您需要进一步的解释,请随时发表评论。谢谢你。

【问题讨论】:

  • @CBroe您是否阅读并理解了这个问题?
  • 是的,我非常认为,是的。
  • @CBroe请帮助我了解如何使用交叉乘法,例如,根据 frameValue 的页面大小是“高度:844,宽度:390”并且 iframe 嵌入的设备是桌面说“1080 x 1920” ?我乐意去学。
  • 当您说要针对宽度进行调整时,桌面高度在这一点上是无关紧要的。 // 当您有两个值元组,并且每个元组中的值之间的比率相同时,交叉乘法允许您根据您的值确定“缺失”的第四个值对于其他三个。

标签: javascript css iframe


【解决方案1】:

您是否有任何理由不使用 CSS 解决方案?这将是一个比设置高度/宽度属性更清洁的解决方案。

#dynamicFrame {
  /* Swap for your desired aspect ratio */
  aspect-ratio 16/9;
  width: 100%;
  height: auto;
}

【讨论】:

  • 谢谢您的回答。我相信用例可能会有所不同。 iframe 变量大小可以是移动的,而窗口大小可以是桌面的。而且所有这些设备都有不同的屏幕尺寸和纵横比,所以我不能有一个硬编码的值。它必须是动态的。
【解决方案2】:

根据屏幕大小和方向,以下公式之一可能有用。 注意:可以使用提供的尺寸确定方向。即景观=宽度>高度

let scale = 0;
// If the window is potrait and the frame is landscape orientation
scale = screenSize.height * (1 / frameValue.height);
// If the window is landscape and the frame is potrait, one of the following applies.
scale = dimensions.height/dimensions.width).toFixed(2);
// OR
scale = dimensions.width/dimensions.height).toFixed(2);

// Set the iFrame Dynamic Scale Value
iframe.style.transform = `scale(${scale})`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2013-07-28
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多