search

Home  >  Q&A  >  body text

css - 一个div进行旋转或缩放后,怎么获取它变形后的宽高?比如:

p{

width: 100px;height: 100px;
transform-origin: 0 0;
transform: rotateZ(45deg);

}
这个p旋转了45度之后,怎么去获取它的宽与高?就是它旋转之后所占的空间

PHP中文网PHP中文网2781 days ago1285

reply all(4)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:31:05

      var test = document.querySelector('#test');
        var rect = test.getBoundingClientRect();
        alert('width:' + rect.width + 'height:' + rect.height);

    I have tried many methods, but this method is the only one that works and I have learned a lot

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:31:05

    //获得视觉上的宽, 高... 原答案直接用了长宽一样的模型, 导致结果出错了
    
    //1.获得原始宽, 高
    var el = document.getElementById('box'),
        h = el.offsetHeight,
        w = el.offsetWidth;
        
    //2.获得旋转角度
    //matrix(cosθ, sinθ, -sinθ, cosθ, 0, 0)
    var transform = window.getComputedStyle(el)['transform'],
        rotate = transform.slice(7, -1).split(',');
    
    //3.计算宽度, 高度
    var lastH = h * rotate[0] + w * rotate[1],   //h * sinθ + w * cosθ
        lastW = h * rotate[1] + w * rotate[0];   //h * cosθ + w * sinθ
    

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:31:05

    The width and height will not be affected after rotation

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:31:05

    Personal opinion, not necessarily correct.

    How to get it before, how to get it again. It’s just that the width and height now look a little different from the previous width and height

    Transform only changes the "look" inside the element, but the element itself is still a rectangle and will always be a rectangle. The space occupied by the element will become the rotated width and height. I wonder if this is the space you are talking about?

    https://jsfiddle.net/qichengzx/zkuucyvj/

    reply
    0
  • Cancelreply