最近公司写了很多产品页面自适应,其中就包括 iframe
嵌套视频。
第一种写法:使用原生 CSS
这个写法是看到掘金的一个博主写的# 使用原生 CSS 实现自适应视频,
html:
<div class="bikeEb-video">
<iframe
scrolling="no"
style="--width: 1300; --height: 760;"
class="bikeEb-video-box"
width="1300" height="760"
src="https://player.bilibili.com/player.html?aid=933716432&bvid=BV1dT4y1o71J&cid=426546980&page=1"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
</div>
css:
.bikeEb-video{
background-color: #000;
text-align: center;
padding: 20px;
box-sizing: border-box;
overflow: hidden;
}
.bikeEb-video-box {
--aspect-ratio: calc(var(--height) / var(--width))!important;
--height-with-units: calc(var(--height) * 1px)!important;
max-width: 100%!important;
height: Min(calc(100vw * var(--aspect-ratio)), var(--height-with-units))!important;
}
其他人的电脑却显示很正常,但是它在我老板的电脑上是不起作用。我也查了兼容性,这个问题不存在,兼容性很高。
这是我老板谷歌浏览器,难道会是因为谷歌浏览器版本问题??但是这也不低啊。虽然我很想知道是啥原因,但还是得赶紧解决问题,我就用了第二种写法——js进行等比例缩放。
第二种写法:js进去行等比例缩放
html:
<div class="bikeEb-video">
<iframe
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen="" class="bikeEb-video-box" frameborder="0" scrolling="no"
src="https://www.bilibili.com/bangumi/play/ep517945?spm_id_from=333.1007.0.0">
</iframe>
</div>
css:
<style type="text/css">
* {
margin: 0;
padding: 0;
}
/* bikeEb-video-start */
.pro_description .content .list.l3 {
width: auto;
margin: 50px auto;
}
.bikeEb-video {
background-color: #000;
text-align: center;
padding: 20px;
box-sizing: border-box;
overflow: hidden;
}
.bikeEb-video-box {
width: 100%;
max-width: 1300px;
height: 760px;
}
/* bikeEb-video-end */
</style>
js:
<script>
const iframeDom = document.querySelector('.bikeEb-video-box')
function getIframeWidthHeigth(width, height) {
if (window.innerWidth < width) {
iframeDom.style.height = window.innerWidth * height / width + 'px'
}else{
iframeDom.style.height = height + 'px'
}
}
getIframeWidthHeigth(1300, 760)
window.onresize = function() {
getIframeWidthHeigth(1300, 760)
}
</script>
所以第一种方法究竟为啥不生效呢??(啊,抓狂)