getComputedStyle和transition

bor*_*lon 6 javascript javascript-events css-transitions

在考虑向铬提交错误时寻找解决方法 -

如果元素具有转换,getComputedStyle则在转换结束之前不会返回您希望返回的内容.

长和短 - 如果我有一个高度为24px的元素,并且添加一个类给它一个80px的高度(转换到和来自),并且两个高度都在样式表中定义 - 如果我设置该类并检查getComputedStyle,它仍然提供非类高度,直到转换结束.

我在这里谈论的一个例子:

<html>
    <head>
        <style>
            #foo {
                display: inline-block;
                background-color: red;
                height: 24px;
                padding: 4px 0;
                width: 200px;
                -webkit-transition-property: height;
                -webkit-transition-timing-function: linear;
                -webkit-transition-duration: 300ms;
            }
            #foo.changed {
                height: 80px;
            }
        </style>
    </head>
    <body>
        <div id="foo"></div>
        <p>before: <span id="before"></span></p>
        <p>after: <span id="after"></span></p>
        <script type="text/javascript">   
            var foo 
            function checkFoo(e) {
                foo.classList.toggle('changed');
                document.getElementById('before').innerText = window.getComputedStyle(foo, null).getPropertyValue("height");
            };

            window.addEventListener('load', function() {
                foo = document.getElementById('foo');

                foo.addEventListener('webkitTransitionEnd', function(e){
                document.getElementById('after').innerText = window.getComputedStyle(foo, null).getPropertyValue("height");
                });

                foo.addEventListener('click', checkFoo, false);
            });
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这个样本的小提琴:http://jsfiddle.net/bobbudd/REeBN/

(注意:这个小提琴只能在webkit中运行,它是我们所针对的一个浏览器信不信由你 - 但我也测试过并在FF中遇到同样的问题)

问题是,我有多种情况需要知道最终的样式(有些人可能会说"计算"样式)才会transitionEnd发生.

或者我猜这是一个更大问题的一部分 - 有很多不同的方法来了解元素的高度,因为它是在特定的时刻,应该getComputedStyle不能得到样式表(或样式属性)所说的属性应该是是?

在你问我是否可以在JS中输入最终数字之前,答案是(不幸的是)没有.

任何人都可以想到在转换结束之前获得最终价值的方法吗?

Asa*_*din 2

这根本不是一个错误。getComputedStyle旨在返回调用属性时客户端呈现的属性值。如果您在转换期间调用它,您将在转换期间获得值,如下所示: http: //jsfiddle.net/REeBN/1/

获取规则设置的最终值的方法是检查规则本身,可能是通过使用cssRules.

这是一个使用的实现window.getMatchedCSSRules

cssRules = window.getMatchedCSSRules(this);
var finalCssRule = "";
for(var i = 0; i < cssRules.length; i++){
    if(cssRules[i].selectorText == "#foo.changed"){
        finalCssRule = cssRules[i];
    }
}
document.getElementById('final').innerText = finalCssRule.cssText;
Run Code Online (Sandbox Code Playgroud)

这是一个演示: http: //jsfiddle.net/REeBN/2/