簡體   English   中英

css過渡到新元素

[英]css transitions on new elements

我找不到在新創建的dom元素上使用css過渡的方法。

假設我有一個空的html文檔。

<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/上看到的那樣,當您單擊該元素時,會立即顯示。

如果我嘗試在timeout()設置類,我經常會找到結果,但對我而言,它似乎更像是javascript和css引擎之間的競爭。 是否有一些特定的事件要聽? 我試圖使用document.body.addEventListener('DOMNodeInserted', ...)但它不起作用。

如何在新創建的元素上應用css過渡?

在Firefox中,它似乎是布局完成和CSS轉換之間的競爭。 Chrome更具可預測性。 如果我在setTimeout()上設置類名,則Chrome始終有效,只有在setTimeout()時間很長時,Firefox才有效。

在Firefox中使用此代碼(甚至使用setTimeout() ),文本立即顯示:

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

    setTimeout(function() {
        a.className = 'fadeIn';
    }, 10);
    return false;
}

但是,如果我通過請求只能在布局后返回的屬性來強制重排,那么它將開始在Firefox中工作:

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

    // request property that requires layout to force a layout
    var x = a.clientHeight;
    setTimeout(function() {
        a.className = 'fadeIn';
    }, 10);
    return false;
}

此外,一旦我請求該屬性強制布局,我甚至可以刪除setTimeout() ,並且動畫可以在Firefox中使用。

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

    // request property that requires layout to force a layout
    var x = a.clientHeight;
    a.className = 'fadeIn';
    return false;
}

您可以在Chrome和Firefox中看到最后一個工作: http//jsfiddle.net/jfriend00/phTdt/

而且,這是一篇討論這種現象的文章: http//gent.ilcore.com/2011/03/how-not-to-trigger-layout-in-webkit.html

我找到了一種更好的方法來觸發布局,並在將元素附加到DOM之后使轉換工作:

window.getComputedStyle(element).opacity;

requestAnimationFrame()https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame )似乎適用於Firefox,Chrome和Safari。 setTimeout()是一個更可靠,更合理的解決方案。 對於舊版瀏覽器(IE8),它將需要Polyfill(當然,不會發生轉換,但CSS仍會發生變化)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM