问题
很多网页中视频是通过iframe来显示的,但跟video标签比,iframe的高度似乎很难控制。
分析
<style type="text/css">
#main {
padding: 20px;
}
.video {
margin: 20px auto;
display: block;
}
</style>
<body>
<div id="main">
<iframe class="video" frameborder="0" allowfullscreen="true" src="http://baishan.oversketch.com/2019/11/05/d07f2f1440e51b9680f4bcfe63b0ab67.MP4"></iframe>
<video class="video" src="http://baishan.oversketch.com/2019/11/05/d07f2f1440e51b9680f4bcfe63b0ab67.MP4">
sorry, your video is missing
</video>
</div>
</body>
如上代码所示的2个iframe块,分别是2个视频源,在页面上显示如下。
很明显看出,iframe高度明显有问题。是不是可以通过video来设置iframe的高度呢?
实现
const videoIframe
= document
.querySelector("iframe")
const videoEle
= document
.createElement("video")
videoEle
.src
= videoIframe
.src
videoEle
.controls
= 'true'
videoEle
.addEventListener('canplay', () => {
const height
= videoEle
.videoHeight
const width
= videoEle
.videoWidth
videoIframe
.height
= height
videoIframe
.width
= width
})
效果
全部代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no,viewport-fit=cover"/>
<title>视频丨罗老师,别这样,别这样,罗老师
</title>
</head>
<style type="text/css">
#main {
padding: 20px;
}
.video {
margin: 20px auto;
display: block;
}
.name {
text-align: center;
}
</style>
<body>
<div id="main">
<div class="name">iframe
</div>
<iframe class="video" frameborder="0" allowfullscreen="true" src="http://baishan.oversketch.com/2019/11/05/d07f2f1440e51b9680f4bcfe63b0ab67.MP4"></iframe>
<div class="name">video
</div>
<video class="video" src="http://baishan.oversketch.com/2019/11/05/d07f2f1440e51b9680f4bcfe63b0ab67.MP4" controls="controls">
sorry, your video is missing
</video>
</div>
</body>
<script type="text/javascript">
const videoIframe = document.querySelector("iframe")
const videoEle = document.createElement("video")
videoEle.src = videoIframe.src
videoEle.controls = 'true'
videoEle.addEventListener('canplay', () => {
const height = videoEle.videoHeight
const width = videoEle.videoWidth
videoIframe.height = height
videoIframe.width = width
})
</script>
</html>