簡體   English   中英

如何在沒有js的css中獲得寬度

[英]how do I get width in css, without js

有沒有一種方法可以僅使用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的圖像,並且使用100vw只會將其拉伸到頁面,而不是容器(其大小也會以與窗口不同的速率改變)拉伸。

有沒有辦法在CSS中獲得元素的寬度? 還是另外一種方法,可以更快地更新javascript,而不會被瀏覽器所不支持的速度?

這似乎有效。 我只是將其放在window.onresize上,以防別人發現它有用。

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

window.onresize = IframeVideoFix;

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

setTimeout(IframeVideoFix, 500);

div的純CSS示例,其基於寬度保持16:9的寬高比。

 * { 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM