繁体   English   中英

如何使用纯 JavaScript 根据宽度调整 div 高度

[英]How resize a div height based on width with pure JavaScript

在调整div的大小时,根据具有约束比率的宽度更改高度

@example div width:300 and height:600 next Ill change width to 400 height change to 800 based on width

您需要找到元素的当前宽度,然后重置其高度。

这是一个简单的例子。 它使用 offsetWidth 来获取当前宽度,但取决于您的用例,可能不够好,也可能不够好。 请参阅https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

通常,offsetWidth 是元素的 CSS 宽度的像素测量值,包括任何边框、填充和垂直滚动条(如果呈现)。 它不包括伪元素的宽度,例如::before 或::after。 如果元素被隐藏(例如,通过将元素或其祖先之一上的 style.display 设置为“none”),则返回 0。

 // Function to set the height of an element proportional to its width // el is the element we are interested in. // ratio is the ratio of width to height that we want function setHeight(el, ratio) { // first we need to find out what the width of el currently is const w = el.offsetWidth; //this will always return an integer console.log(w); el.style.height = (w * ratio) + 'px'; //note you could also investigate getBoundingClientRect().width for a more general case when there have been transformations }
 <div class="element" style="width: 200px; height: 200px; background-color: magenta;" onclick="setHeight(this, 600/300);">Click me</div>

offsetWidth 始终返回 integer,当然可能还有其他一些计算使宽度不是 integer。 另外,如果发生了转变怎么办? 要更全面地了解尺寸及其含义,请参阅https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM