如何使用纯 JavaScript 根据宽度调整 div 高度
How resize a div height based on width with pure JavaScript
调整大小时 div
根据宽度更改高度,约束比率
@example div width:300
和 height:600
接下来我将宽度更改为 400
高度更改为 800
基于宽度
您需要找到元素的当前宽度,然后重新设置它的高度。
这是一个简单的例子。它使用 offsetWidth 来获取当前宽度,但取决于您的用例,它可能不够好,也可能不够好。参见 https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth
Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered). It does not include the width of pseudo-elements such as ::before or ::after. If the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.
// 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 总是returns一个整数,当然也可能有一些其他的计算使得宽度不是整数。另外,如果发生了转变怎么办?要更全面地了解维度及其含义,请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
调整大小时 div
根据宽度更改高度,约束比率
@example div width:300
和 height:600
接下来我将宽度更改为 400
高度更改为 800
基于宽度
您需要找到元素的当前宽度,然后重新设置它的高度。
这是一个简单的例子。它使用 offsetWidth 来获取当前宽度,但取决于您的用例,它可能不够好,也可能不够好。参见 https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth
Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered). It does not include the width of pseudo-elements such as ::before or ::after. If the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned.
// 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 总是returns一个整数,当然也可能有一些其他的计算使得宽度不是整数。另外,如果发生了转变怎么办?要更全面地了解维度及其含义,请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect