问题
I've read several similar questions on SO regarding Bootstrap's fade
classes, but none of them seem to address my issue.
I understand that the fade animation in Bootstrap 3 works by switching opacity
between 0
and 1
when you add the .in
class to an element that already has a .fade
class. This works fine for me when dealing with an element that already exists in the HTML (for example, this JS Fiddle demo).
The problem is that the transition doesn't seem to happen when the element is created dynamically with Javascript. For example, the following code will create and display an alert, but the CSS transition doesn't happen (tested in both Chrome and Firefox). If I manually add and remove the in
class in Dev Tools, the fade works fine:
$('<div class="alert fade">This is a test</div>')
.appendTo($someElement)
.addClass('in');
Clearly the .addClass()
function is working because the alert gets the in
class and is displayed, but the transition doesn't happen. Any idea how I can get it to work?
For an editable demo, see this pen on CodePen.
回答1:
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');
回答2:
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?
来源:https://stackoverflow.com/questions/20942855/fade-in-dynamically-generated-content-with-bootstrap-3