【问题标题】:Calculate div width/height when inside a zoom/scale transform在缩放/缩放变换中计算 div 宽度/高度
【发布时间】:2019-02-03 20:02:52
【问题描述】:

我在另一个 div 内有一个 div,并应用了变换比例。

应用比例后,我需要获取此 div 的宽度。 .width() 的结果是元素的原始宽度。

请查看此代码笔: https://codepen.io/anon/pen/ZMpBMP

问题图片:

希望这足够清楚,谢谢。代码如下:


HTML

<div class="outer">
  <div class="inner">
  </div>
</div>

CSS

.outer {
  height: 250px;
  width: 250px;
  background-color: red;
  position: relative;
  overflow: hidden;
}

.inner {
  background-color: green;
  height: 10px;
  width: 10px;
  transform: translate(-50%);
  position: absolute;
  top: 50%;
  left: 50%;

  transform: scale(13.0);
}

JS

$(function() {

   var width = $('.inner').width();

   // I expect 130px but it returns 10px
   //
   // I.e. It ignores the zoom/scale
   //      when considering the width
   console.log( width );

});

【问题讨论】:

标签: javascript jquery html css scale


【解决方案1】:

您需要计算出的值。这可以在 CSS 中完成。

使用 calc() 计算 &lt;div&gt; 元素的宽度,该元素可以是任何元素:

#div1 {
    position: absolute;
    left: 50px;
    width: calc(100% - 100px);
    border: 1px solid black;
    background-color: yellow;
    padding: 5px;
    text-align: center;
}

我发现了这个关于这个主题的内容。

Can i use Calc inside Transform:Scale function in CSS?


对于 JS:

How do I retrieve an HTML element's actual width and height?

【讨论】:

  • 对不起,我试图在 JS 中获取内部绿色框元素的宽度而不是 css
【解决方案2】:

我通过这个达到了你的 130

var x = document. getElementsByClassName('inner');
var v = x.getBoundingClientRect();
width = v.width;

【讨论】:

    【解决方案3】:

    使用getBoundingClientRect()

    $(function() {
    
       var width = $('.inner')[0].getBoundingClientRect();
       // I expect 130px but it returns 10px
       //
       // I.e. It ignores the zoom/scale
       //      when considering the width
       console.log(width.width);
    
    });
    

    https://jsfiddle.net/3aezfvup/3/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      相关资源
      最近更新 更多