I'm OK at JavaScript but bad at CSS and completely new to transitions and fades.
Examples that I've looked at that were simple enough to understand at a glance did fading both in and out.
Examples that did closer to what I want didn't seem as simple to grok so quickly, but then again those questions didn't ask specifically and only what I'm asking here.
I'll set the text and initiate the fading with JS but is there a way where that's all I have to do, ignoring when the fade is finished?
I've tried just removing the transition style and setting the opacity, then adding the text and putting the transition style back in and setting the new opacity, which doesn't work:
span.style.transition = '';
span.style.opacity = '1';
span.textContent = 'fading message';
span.style.transition = 'opacity 1s';
span.style.opacity = '0';
答案 0 :(得分:1)
根据评论,我相信这是您正在寻找的解决方案:
document.getElementById('btn_click').addEventListener('click', function() {
var span = document.getElementById('fader');
span.style.transition = 'none';
span.style.opacity = '1';
span.textContent = 'fading message';
/* This line seems to 'reset' the element so that the transition can be run again. */
void span.offsetWidth;
span.style.transition = 'opacity 1s';
span.style.opacity = '0';
});
<div>
<span id="fader"></span><br/>
<button id="btn_click">Click to fade</button>
</div>
特别注意行void span.offsetWidth;
,它似乎做了某种重置。我发现了here。