Retrieve width/height of a css3 scaled element

大憨熊 提交于 2019-11-26 16:49:06

问题


I'm fighting against an oddity (I think) of the offsetWidth property.
this is the scenario:

I've got, let's say, a span tag, in my js, at a certain point I perform a css3 transform to this element, like:

        el.set('styles', {
            'transform':'scale('+scale+', '+scale+')',      /* As things would be in a normal world */
            '-ms-transform':'scale('+scale+', '+scale+')',      /* IE 9 */
            '-moz-transform':'scale('+scale+', '+scale+')',         /* Moz */
            '-webkit-transform':'scale('+scale+', '+scale+')',  /* Safari / Chrome */
            '-o-transform':'scale('+scale+')'       /* Oprah Winfrey */ 
        }); 
        w = el.getWidth();
        console.log('after scaling: ' + w);

at this point the log returns me fuzzy values, like it doesn't know what to say.
any suggestion?


回答1:


getBoundingClientRect() returns the correct values for me.

jsFiddle.




回答2:


Transforms don't affect the intrinsic CSS properties, so you are seeing correct behavior. You need to look at the Current Transformation Matrix - as returned from getComputedStyle().webkitTransform in order to figure out how big something has been scaled.

Update: In Firefox 12 and later and Chrome/Safari - as Alex says below, you can use getBoundingClientRect() to take into account any transforms applied to an element

The scale transition starts from 50%/50% because that's the default & correct behavior. If you want it to start from the origin, then you need to set transform-origin: 0% 0%;




回答3:


I take it the span tag has display:block? transforms are only supposed to work for block elements. When I goto console and load jquery (just for ease) and do this:

$('span#foo').css({"-webkit-transform": "scale(2.0, 2.0)"})

nothing happens. But if I do this:

$('span#foo').css('display','block').css({"-webkit-transform": "scale(2.0, 2.0)"})

suddenly it changes, and offsetHeight increases. Disappointingly, the offset hight goes from 16 to 19, and not to 32 (although the visual appearance is double the size and maybe it is accurate) — but at least it does appear to work as advertised.




回答4:


getBoundingClientRect() didn't work for me (in Chrome 49).

This answer led me to another solution to my problem: https://stackoverflow.com/a/7894886/1699320

function getStyleProp(elem, prop){
    if(window.getComputedStyle)
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    else if(elem.currentStyle) return elem.currentStyle[prop]; //IE
}
getStyleProp(element, 'zoom')    //gives zoom factor to use in calculations


来源:https://stackoverflow.com/questions/5834624/retrieve-width-height-of-a-css3-scaled-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!