首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >给定一个外部div和一个内部div的高宽比,如何计算内部div的最大大小?

给定一个外部div和一个内部div的高宽比,如何计算内部div的最大大小?
EN

Stack Overflow用户
提问于 2022-07-27 19:29:26
回答 4查看 57关注 0票数 -1

我有两个盒子/电视。一个外盒子和一个内盒子。内盒始终包含在外盒内。提供以下信息:

外盒: width=200 height=100

内箱:纵横比=16/9

在JavaScript中,如何计算内部框的最大大小以保持其纵横比?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2022-07-27 19:58:41

获取外部长宽比,并使用它来确定内箱是否需要相对于外框而言是字母框(景观,较短)还是柱盒(纵向,窄)。在此基础上计算内部尺寸。您还可以计算中心所需的偏移量。

代码语言:javascript
复制
const outerWidth = 200;
const outerHeight = 100;
const aspectRatio = 16/9;

let innerWidth, innerHeight, innerTop, innerLeft;

if (outerWidth / outerHeight > aspectRatio) {
    innerWidth = outerHeight * aspectRatio;
    innerHeight = outerHeight;
    innerLeft = (outerWidth - innerWidth) / 2;
    innerTop = 0;
} else {
    innerWidth = outerWidth;
    innerHeight = outerWidth / aspectRatio;
    innerLeft = 0;
    innerTop = (outerHeight - innerHeight) / 2;
}
票数 1
EN

Stack Overflow用户

发布于 2022-07-27 19:51:00

我知道您是专门要求JavaScript的,但是这是非常好的 simple to do in CSS with aspect-ratio,如果您需要JS中的维度,您可以只获取呈现的维度。

代码语言:javascript
复制
const pre = document.querySelector('pre');
const aspect = document.querySelector('.ratio');

// getboundingClientRect also works.
const dimensions = window.getComputedStyle(aspect);

pre.textContent = `width: ${dimensions.width}, height: ${dimensions.height}`;
代码语言:javascript
复制
.container {
  width: 200px;
  height: 100px;
}

.ratio {
   aspect-ratio: 16 / 9;
   /* Just keeping it within the constaints */
   max-height: 100px;
   border: 1px solid red;
}

.no-ratio {
   border: 1px solid red;
}
代码语言:javascript
复制
<div class="container">
  <div class="ratio">
    16:9
  </div>
</div>
<pre></pre>

<div class="container">
  <div class="no-ratio">
    Not 16:9.
  </div>
</div>
<pre></pre>

票数 2
EN

Stack Overflow用户

发布于 2022-07-27 19:40:35

代码语言:javascript
复制
let outerBoxWidth = 200;
let outerBoxHeight = 100;
let maxInnerBoxWidth = ((outerBoxWidth / 16) | 0);

let maxInnerBoxHeight = ((outerBoxHeight / 9) | 0);

let widthLower = maxInnerBoxHeight > maxInnerBoxWidth;
if(widthLower){
  let innerBoxHeight = 9 * maxInnerBoxWidth;
  let innerBoxWidth = 17 * maxInnerBoxWidth;
}else{
  let innerBoxHeight = 9 * maxInnerBoxHeight;
  let innerBoxWidth = 17 * maxInnerBoxHeight;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73143651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档