I've been trying to get some text to fade in from opacity 0 to 100, but I can't seem to get it to work right. Credits to the person for the original fadeOut version.
Here's the code...
fadeIn = function(id, speed) {
var s = document.getElementById(id).style;
s.opacity = 0;
(function fade() {(s.opacity+= .1)<100?s.display="inline":setTimeout(fade,speed)})();
}
I think there are 2 problems, 1 the opacity values vary from 0...1
not 0..100
also when opacity is 1 you need to stop the loop.
Second, s.opacity
returns a string, so since you are using +
operator you need to convert the value to a string else a string concatenation will be performed
fadeIn = function(id, speed) { var s = document.getElementById(id).style; s.opacity = 0; (function fade() { (s.opacity = +s.opacity + .1) >= 1 ? s.display = "inline" : setTimeout(fade, speed) })(); } fadeIn('s', 500)
<div id="s">asdfsadf</div>
All you have to do is set an interval and then count up to 100 by your speed/100 in increments.
function fadeIn(id, speed) { var max = 100, count = 0; var increment = speed / max; var obj = document.getElementById(id); var interval = setInterval(function() { obj.style.opacity = (count / max); if (count == max) { clearInterval(interval); } count++; }, increment); }
#faded { opacity: 0; }
<div id="faded">Fade me in</div> <button onclick="fadeIn('faded', 3000)">Fade it in</button>
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.