[英]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.