How to make fadeOut effect with pure JavaScript

后端 未结 5 552
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 01:59

I\'m trying to make fadeOut effect for a div with pure JavaScript.

This is what I\'m currently using:

//Imagin         


        
5条回答
  •  隐瞒了意图╮
    2020-11-29 02:17

    Initially when there's no opacity set, the value will be an empty string, which will cause your arithmetic to fail. That is, "" < 0.1 == true and your code goes into the clearInterval branch.

    You can default it to 1 and it will work.

    function fadeOutEffect() {
        var fadeTarget = document.getElementById("target");
        var fadeEffect = setInterval(function () {
            if (!fadeTarget.style.opacity) {
                fadeTarget.style.opacity = 1;
            }
            if (fadeTarget.style.opacity > 0) {
                fadeTarget.style.opacity -= 0.1;
            } else {
                clearInterval(fadeEffect);
            }
        }, 200);
    }
    
    document.getElementById("target").addEventListener('click', fadeOutEffect);
    #target {
        height: 100px;
        background-color: red;
    }
    Click to fade

    An empty string seems like it's treated as a 0 by JavaScript when doing arithmetic and comparisons (even though in CSS it treats that empty string as full opacity)

    > '' < 0.1
    > true
    
    > '' > 0.1
    > false
    
    
    > '' - 0.1
    > -0.1
    

    Simpler Approach We can now use CSS transitions to make the fade out happen with a lot less code

    const target = document.getElementById("target");
    
    target.addEventListener('click', () => target.style.opacity = '0');
    // If you want to remove it from the page after the fadeout
    target.addEventListener('transitionend', () => target.remove());
    #target {
        height: 100px;
        background-color: red;
        transition: opacity 1s;
    }

    Some text before

    Click to fade

    Some text after

提交回复
热议问题