fade in and fade out in pure javascript without jquery

会有一股神秘感。 提交于 2019-12-05 07:06:38

I'd suggest using CSS animation

@-webkit-keyframes fadeout {
    0% {opacity:1;}
    100% {opacity:0;}
}
@keyframes fadeout {
    0% {opacity:1;}
    100% {opacity:0;}
}
.fadeOut {
  opacity:0;
  -moz-animation   : fadeout 1s linear;
  -webkit-animation: fadeout 1s linear;
  animation        : fadeout 1s linear;
}

You only need to add fadeOut class to the element

If you want a pure JavaScript solution, you can use this:

http://jsfiddle.net/3weg2zj1/1/

HTML

<div id="box"></div>

CSS

#box {
    width:100px;
    height:100px;
    background-color:blue;
}

JavaScript

var box = document.getElementById('box');

function fadeOutIn(elem, speed ) {

    if (!elem.style.opacity) {
        elem.style.opacity = 1;
    } // end if

    var outInterval = setInterval(function() {
        elem.style.opacity -= 0.02;
        if (elem.style.opacity <= 0) {
            clearInterval(outInterval);
            var inInterval = setInterval(function() {
                elem.style.opacity = Number(elem.style.opacity)+0.02;
                if (elem.style.opacity >= 1)
                    clearInterval(inInterval);
            }, speed/50 );
        } // end if
    }, speed/50 );

} // end fadeOut()

fadeOutIn(box, 2000 );
  • in general, you have to capture the interval identifier returned by the setInterval() call so that you can cancel it later. Note that, in the above code, this involves closuring, both on outInterval and inInterval.
  • for this specific code, you can test when opacity is at or below a lower threshold (I used zero), and then clear the existing interval process, and kick off a new one to reverse the animation.
  • in the reverse interval process, you can increment the opacity, and then test against an upper threshold to decide when to clear the new interval process.
  • I ran into a bizarre issue with trying to increment elem.style.opacity: the += operator was refusing to work. After probably 10min of sitting and staring (and some experimentation), I finally figured out that elem.style.opacity is always being forced to be a string (perhaps all CSS-linked properties behave this way...), and so the + operator (and by extension the += operator) was doing string concatenation, which, under the naive LoC of elem.style.opacity += 0.02;, was turning into elem.style.opacity = elem.style.opacity+0.02;, which, if we assume elem.style.opacity was at '0.02', was turning into elem.style.opacity = '0.02'+0.02;, which was turning into elem.style.opacity = '0.020.02';, which the browser JavaScript engine (ahem) generously parses as 0.020 (because it requires a valid numeric value for the CSS opacity property!), which resulted in the opacity getting stuck at 0.02. Holy crap! That's why I had to add the cast-to-number before doing the addition.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!