在我的HTML代码中,我将我的Iframe宽度值设置为宽度的95%。我希望高度根据设置的宽高比动态调整大小。我已经制作了一个javascript脚本来尝试动态调整大小,但是当我运行我的HTML时,它不会调整高度。
这是我的iframe的html:
<div class="video">
<tr>
<td>
<iframe src="https://embed.theguardian.com/embed/video/news/video/2016/dec/27/cassetteboy-remix-the-news-2016-review-special-video" scrolling="no" onload="resizeiframe(this);" allowfullscreen></iframe>
</td>
</tr>
</div>
这是我的css:
.video {
}
.video iframe {
align: center;
width: 95%;
margin-top: 180px;
float: top;
position: relative;
}
这是我的javascript:
<script>
//this is javascript
//it is used to dynamically resize the height of the iframes based on screen width
function resizeiframe(object) {
//assign the aspect ratio to a variable
private float aspectratio = (6/19);
//set the objects height to the object's width multiplied by the aspect ratio
object.style.height = (object.style.width * aspectratio);
}
</script>
有人可以帮忙吗?
答案 0 :(得分:1)
两个解决方案
首先,您的原始JS遇到了一些问题:
iframe
的宽度(使用element.offsetWidth
或类似内容)px
等)aspectratio
键入private float
而不是var
或private aspectratio: number;
(Typescript) - 除非您使用的是其他超集JS语言,并且它不是& #39;标记在问题中。 JavaScript:(修改原文)
function resizeiframe(object) {
//assign the aspect ratio to a variable
var aspectratio = (6/19);
//set the objects height to the object's width multiplied by the aspect ratio
object.style.height = (object.offsetWidth * aspectratio) + "px";
}
// This is just quick and dirty to grab the element -- do something better
resizeiframe(document.getElementsByTagName("iframe")[0]);
通过JavaScript执行此操作可能还需要您在resizeiframe
上致电window.resize
以补偿用户调整浏览器窗口的大小。
<强> OR 强>
如果您不反对使用vw
(视口宽度单位)而不是{{{},也可以使用仅限CSS 解决方案(无需JavaScript)来实现1}}(像素)。
<强> CSS:强>
px
<强> HTML 强>
iframe {
width: 95vw;
height: calc(95vw*(6/19));
}
使用此解决方案,浏览器大小调整将自动处理。
注意:在这两个解决方案中,我删除了<iframe src="https://embed.theguardian.com/embed/video/news/video/2016/dec/27/cassetteboy-remix-the-news-2016-review-special-video" scrolling="no" onload="resizeiframe(this);" allowfullscreen></iframe>
包装元素以简化答案,但这可以轻松添加回来。
答案 1 :(得分:0)
你应该添加px。
object.style.height = (object.style.width * aspectratio) + "px";