【问题标题】:Issue getting CSS calc width with JS使用 JS 获取 CSS 计算宽度的问题
【发布时间】:2019-07-08 22:53:36
【问题描述】:

我需要制作一个基于屏幕宽度的方形元素。要将高度设置为与宽度相同,我尝试使用 JS,但似乎有点错误。这是一个例子

var square = document.getElementById('square');
square.style.height = square.clientWidth + 'px';
#square {
  background-color: blue;
  width: calc(20vw - 16px);
  padding: 8px;
}
<div id="square">Element</div>

上面的蓝色“正方形”不是正方形。有谁能解释为什么?我尝试了scrollWidthoffsetWidth 而不是clientWidth,结果相似。我也没有让style.width 给出正确的号码。

即使您在 Chrome 上检查蓝色方块,您也会得到一个高度和宽度的数字,它们很接近但仍然非常不同。

【问题讨论】:

    标签: javascript html css css-calc


    【解决方案1】:

    两个问题。首先你需要考虑填充,所以添加box-sizing:border-box然后你使用vw单位定义宽度,所以当你第一次打开页面时你会有一个正方形only从不调整浏览器的大小。

    var square = document.getElementById('square');
    square.style.height = square.clientWidth + 'px';
    #square {
      background-color: blue;
      width: calc(20vw - 16px);
      padding: 8px;
      box-sizing:border-box;
    }
    <div id="square">Element</div>

    如果您想要一个保持窗口大小调整的正方形,您需要使用相同的指定值,而不是以像素为单位的计算值 (How do you read CSS rule values with JavaScript?)

    或者在resize时改变值:

    var square = document.getElementById('square');
    square.style.height = square.clientWidth + 'px';
    
    window.onresize=function() {
      square.style.height = square.clientWidth + 'px';
    };
    #square {
      background-color: blue;
      width: calc(20vw - 16px);
      padding: 8px;
      box-sizing:border-box;
    }
    <div id="square">Element</div>

    作为旁注,您可以考虑 CSS 变量仅指定一次相同的值或检查:Maintain the aspect ratio of a div with CSS

    #square {
      --v:calc(20vw - 16px);
      background-color: blue;
      width: var(--v);
      height: var(--v);
      padding: 8px;
      box-sizing:border-box;
    }
    <div id="square">Element</div>

    【讨论】:

    • 需要用到js吗?
    • @wadie 不是,但我正在回答问题为什么
    • 当然,只是想确保我没有遗漏任何东西。谢谢!
    【解决方案2】:

    你可以对高度使用相同的计算方法

    width: calc(20vw - 16px);
    height: calc(20vw - 16px);
    

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2012-03-26
      • 2014-03-26
      相关资源
      最近更新 更多