简体   繁体   中英

'FadeIn' and 'FadeOut' don't work

I've created two functions called 'FadeIn' and 'FadeOut' because i can't use jQuery but they don't work, i don't know why. They directly set the opacity to 0 or 1 without doing it gradually. This is the code:

function fadeIn(el){
    var val = 0;
    document.getElementById(el).style.opacity = val;
    function fade(){
        val += .1;
        document.getElementById(el).style.opacity = val;
        if (val < 1){
            setTimeout(fade(), 90);
        }
    }
    fade();   
}

function fadeOut(el){
    var val = 1;
    document.getElementById(el).style.opacity = val;
    function fade(){
        val -= .1;
        document.getElementById(el).style.opacity = val;
        if (val > 0){
            setTimeout(fade(), 90);
        }
    }
    fade();   
}

You were very close. when you give fade() instead of fade as the first argument, the function invokes itself, and your setTimeout() does nothing. this should work:

function fadeIn(el){
    var val = 0;
    document.getElementById(el).style.opacity = val;
    function fade(){
        val += .1;
        document.getElementById(el).style.opacity = val;
        if (val < 1){
            setTimeout(fade, 90); // A Small fix to your code
        }
    }
    fade();
}

fadeOut() will be fixed the same way.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM