问题
CSS transitions will not apply if you set the display property of an element to block immediately before changing the property with the transition attached. You can see the issue in the following example:
var dom = {};
dom.creative = document.getElementById('creative');
dom.creative.style.display = 'block';
dom.creative.style.opacity = 1;
#creative {
display: none;
opacity: 0;
transition: opacity 2s;
}
<div id="creative">
<span>Sample text</span>
</div>
The issue can be fixed by forcing a repaint on the element:
var dom = {};
dom.creative = document.getElementById('creative');
dom.creative.style.display = 'block';
var a = dom.creative.offsetHeight; /* <-- forces repaint */
dom.creative.style.opacity = 1;
#creative {
display: none;
opacity: 0;
transition: opacity 2s;
}
<div id="creative">
<span>Sample text</span>
</div>
This solution is not good because it adds the need of a non intuitive extra line of code everytime you need the display transition combination.
A SO user found an elegant solution (https://stackoverflow.com/a/38210213/6004250) to this problem replacing the transition by the animation property. I'm still curious about making it work together with CSS transitions (because they are easier to understand and to use). Any ideas?
来源:https://stackoverflow.com/questions/38213118/workaround-for-display-block-and-css-transitions-work-properly