CSS/HTML通过Javascript动态调整Iframe的大小
在我的HTML代码中,我将Iframe宽度值设置为宽度的95%。我希望高度根据设置的纵横比动态调整大小。我制作了一个javascript脚本来尝试动态调整大小,但是当我运行HTML时,它不会调整高度 以下是我的iframe html:CSS/HTML通过Javascript动态调整Iframe的大小,javascript,html,css,iframe,Javascript,Html,Css,Iframe,在我的HTML代码中,我将Iframe宽度值设置为宽度的95%。我希望高度根据设置的纵横比动态调整大小。我制作了一个javascript脚本来尝试动态调整大小,但是当我运行HTML时,它不会调整高度 以下是我的iframe html: <div class="video"> <tr> <td> <iframe src="https://embed.theguardian.com/embed/video/ne
<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>
下面是我的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>
有人能帮忙吗?你应该添加px
object.style.height = (object.style.width * aspectratio) + "px";
两种解决方案
首先,您的原始JS存在一些问题:
您没有正确获取iframe的宽度,请使用element.offsetWidth或类似内容
设置宽度px等时,需要指定单位。
您将aspectratio错误地输入为private float,而不是var或private aspectratio:number;Typescript-除非您使用的是另一种超集JS语言,并且问题中没有标记它。
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执行此操作可能还需要调用window.resize上的resizeiframe以补偿用户调整浏览器窗口的大小
或
如果您不反对使用vw视口宽度单位而不是px像素,也可以使用不需要JavaScript的仅CSS解决方案来实现这一点
CSS:
HTML
使用此解决方案,浏览器大小自动调整
注意:在两种解决方案中,我都删除了.video wrapper元素以简化答案,但这可以很容易地添加回去。既然css已经是百分比,为什么需要显式调整它的大小?还有,私有浮动不给你错误吗?或者你正在编译你的代码?private float x不是有效的javascript变量语法。我将private float更改为var,但仍然无效。object.style.width未定义,因此您的高度始终设置为0。顺便问一下,你们有不同的视频吗?复制你的代码会让我在vid使用的引导程序中遇到很多错误。你可能需要有一个固定的高度来开始工作。您是否尝试过使用css类而不是直接放置样式属性?
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]);
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>