I think this is a pretty simple question.
I have a script which replace a text on my website. I would love to add a fade-effect while replacing. What should I do?
var target = document.getElementById('target'); var titles = [ 'Text1', 'Text2', 'Text3' ]; function newTitle () { var i = (Math.random() * titles.length) | 0; target.innerText = titles[i]; } newTitle();
<p id="target"></p> <button onclick="newTitle()">Replace</div>
Here is an example. I utilized setInterval
and change the text's opacity
over time - just vanilla JavaScript
var target = document.getElementById('target'); var titles = [ 'Text1', 'Text2', 'Text3' ]; function newTitle() { document.getElementById("trigger").disabled = true; var i = (Math.random() * titles.length) | 0; var width = 0; var opacity = 0; target.style.opacity = opacity; target.innerText = titles[i]; var c = setInterval(fade, 100); function fade() { if (opacity>1) { clearInterval(c); document.getElementById("trigger").disabled = false; return; } else { opacity += 0.1; target.style.opacity = opacity; } } }
<p id="target">Text1</p> <button id="trigger" onclick="newTitle()">Replace</div>
Add a CSS effect to transition
, specific for opacity
.
In your function, change the element opacity to 0.
Add a timeout before changing the text (use the same time you added in the transition effect).
When timer ends, change the text and opacity back to 1.
See below code:
var target = document.getElementById('target'); var titles = [ 'Text1', 'Text2', 'Text3' ]; function newTitle () { var i = (Math.random() * titles.length) | 0; target.style.opacity = "0"; setTimeout(function(){ target.innerText = titles[i]; target.style.opacity = "1"; }, 600); } newTitle();
#target{ transition: opacity .6s ease; }
<p id="target"></p> <button onclick="newTitle()">Replace</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.