Fade in dynamically generated content with Bootstrap 3

╄→尐↘猪︶ㄣ 提交于 2019-12-06 01:20:08

The problem you are seeing is that by the time the browser renders the element, you have already added the "transition" class. Adding an element doesn't cause it to be rendered until it needs to be. Once an element has been rendered with the "starting value" and also has the transition css property set (from the "initial" classes), you can then add the other class to trigger your animation. You need the browser to have rendered the initial state before you add the other class or there is nothing to animate "from" and it comes in at it's full transition value.

You might try reading a value from that element like width which should force a repaint before you add the other class: http://codepen.io/anon/pen/hGrFe

If you were going to take anthony's approach, I would suggest using requestAnimationFrame instead of setTimeout as that is guaranteed to be after a repaint has happened (assuming browser support for raf).

To save some repeating yourself, you could write your own repaint method on jQuery:

jQuery.fn.repaint = function() {
    // getting calculated width forces repaint (hopefully?!)
    this.width();
    // return chain
    return this;
};

// then later:
$('<div class="alert fade">This is a test</div>')
    .appendTo($someElement)
    .repaint()
    .addClass('in');
antony

Try changing your javascript to something like this:

var $alert = $('<div class="alert alert-success fade out">Why does this box not fade in?</div>');

$('#container').append($alert);

window.setTimeout(function () {
    $alert.addClass('in');
}, 0);

Here's some further reading that explains what's going on.

http://ejohn.org/blog/how-javascript-timers-work/

Why is setTimeout(fn, 0) sometimes useful?

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