新元素上的 css 过渡 [英] css transitions on new elements
问题描述
我找不到在新创建的 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屋!