workaround for display block and css transitions work properly

被刻印的时光 ゝ 提交于 2020-01-07 00:35:21

问题


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

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