css转换新元素 [英] css transitions on new elements

查看:138
本文介绍了css转换新元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到在新创建的dom元素上使用css转换的方法。

I cannot find a way to use css transitions on newly created dom elements.

假设我有一个空的html文档。

let's say I have an empty html document.

<body>
    <p><a href="#" onclick="return f();">click</a></p>
</body>

我也有这个css

#id {
    -moz-transition-property: opacity;
    -moz-transition-duration: 5s;
    opacity: 0;
}

#id.class {
    opacity: 1;
}

和此js

function f() {
    var a = document.createElement('a');
    a.id = 'id';
    a.text = ' fading in?';
    document.getElementsByTagName('p')[0].appendChild(a);
    // at this point I expect the span element to be with opacity=0

    a.className = 'class';
    // now I expect the css transition to go and "fade in" the a        

    return false;
}

但您可以在 http://jsfiddle.net/gwxkW/1/ 当您点击元素即时出现。

but, as you can see on http://jsfiddle.net/gwxkW/1/ when you click the element appears instantaneously.

如果我尝试在 timeout()我经常设置类找到结果,但对我来说, javascript和css引擎之间。有什么具体的事情要听吗?我尝试使用 document.body.addEventListener('DOMNodeInserted',...)但它不工作。

If I try to set the class in a timeout() i often find the result, but to me it seems more a race between javascript and the css engine. Is there some specific event to listen? I tried to use document.body.addEventListener('DOMNodeInserted', ...) but it's not working.

如何对新创建的元素应用CSS转换?

How can I apply css transitions on newly created elements?

推荐答案

requestAnimationFrame() https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame )似乎可以在Firefox,Chrome和Safari上使用。一个更可靠,逻辑的解决方案, setTimeout()。对于旧的浏览器(IE8),它将需要一个Polyfill(自然,不会发生转换,但CSS仍然会改变)。

requestAnimationFrame() (https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame) appears to work across Firefox, Chrome and Safari. A more reliable, logical solution that setTimeout(). For older browsers (IE8), it will require a Polyfill (naturally, the transition won't occur, but the CSS will still change).

这篇关于css转换新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆