首页 > 解决方案 > 如何在没有js的情况下在css中获得宽度

问题描述

有没有办法只在css中检索元素的宽度,而不使用javascript。我知道如何使用document.getElementsById("iframe").offsetWidth并将其设置为重复运行。

var video = document.getElementsByClassName("video");
var ratio = 16/9;
var milliseconds = 100;

setInterval(function(){
  IframeSizeRatioFix(video, ratio);
}, milliseconds);

function IframeVideoFix(video, ratio){
  for(i = 0; i < video.length; i++){
    video[i].style.height = video[i].offsetWidth/ratio;
  }
}

但即使我将毫秒设置为 1 或 0.001,浏览器也无法处理此速度并跳过更新,并且当用户调整窗口大小时,iframe 大小的变化会有点锯齿状,并且跳跃很多。我想知道是否有办法height: calc(100% / (16/9));在 css 中使用该函数,但 100% 似乎显示图像被压扁,并且使用100vw只是将其拉伸到页面,而不是容器(它也以与窗口不同的速率改变大小) .

有没有办法在css中获取元素宽度?或者,一种更快地更新javascript的方法,而不是浏览器不支持的速度?

标签: javascripthtmlcss

解决方案


基于宽度保持 16:9 纵横比的 div 的纯 CSS 示例。

* {
  box-sizing: border-box;
}

.aspect-16-9 {
  position: relative;
  padding-bottom: 56.25%;
  overflow: hidden;
}

.aspect-content {
  position: absolute;
  width: 100%;
  height: 100%;
  
  /*and some styling*/
  padding: 15px;
  overflow-y: auto;
  background: #DDD;
}
<div style="width: 100%; max-width: 960px; padding: 20px;">
  <div class="aspect-16-9">
    <div class="aspect-content">
      Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by
      their place and supplies it with the necessary regelialia. It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic
      life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar. The Big Oxmox advised her not to do so, because there were thousands of bad Commas, wild Question Marks and devious Semikoli,
      but the Little Blind Text didn’t listen. She packed her seven versalia, put her initial into the belt and made herself on the way. When she reached the first hills of the Italic Mountains, she had a last view back on the skyline of her hometown
      Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, the Line Lane. Pityful a rethoric question ran over her cheek, then
    </div>
  </div>
</div>


推荐阅读