简体   繁体   中英

Opacity Style doesn't work in a call back Java Script?

The loop is working ok after callback of assigned eventlistener function fade() but console show me that opacity doesn't modify when the value is changing. What i'm doing wrong?

function fade(element) {

    var easeIn = 0.01;
    var easeOut = 0.01;

    for (alpha = 1; alpha >= 0.2 ; alpha -= easeIn){
        element.target.style.opacity = String(alpha);
        console.log(alpha, element.target);
    }

    for (alpha = 0.2; alpha <= 1 ; alpha += easeOut){
        element.target.style.opacity = alpha;
        console.log(alpha, element.target);
    }    
}

Your loop runs synchronously, and the browser batches style changes - the display will only update once all Javascript has completed, and by that time, the opacity will be back to 1, so visually, there won't appear to have been any changes.

Add a small delay inside the loops instead:

 const delay = ms => new Promise(res => setTimeout(res, ms)); async function fade(element) { var easeIn = 0.01; var easeOut = 0.01; for (alpha = 1; alpha >= 0.2; alpha -= easeIn){ element.style.opacity = String(alpha); await delay(20); } for (alpha = 0.2; alpha <= 1; alpha += easeOut){ element.style.opacity = alpha; await delay(20); } } const elm = document.querySelector('button'); elm.addEventListener('click', () => { fade(elm); });
 <button>click</button>

(note that a variable named element should probably actually be an element , else you may well cause confusion for others who read the code, including you later)

For multiple buttons, make sure you declare the alpha variable, else it'll be implicitly global and shared by all listeners:

 const delay = ms => new Promise(res => setTimeout(res, ms)); async function fade(element) { var easeIn = 0.01; var easeOut = 0.01; for (let alpha = 1; alpha >= 0.2; alpha -= easeIn){ element.style.opacity = String(alpha); await delay(20); } for (let alpha = 0.2; alpha <= 1; alpha += easeOut){ element.style.opacity = alpha; await delay(20); } } for (const elm of document.querySelectorAll('button')) { elm.addEventListener('click', () => { fade(elm); }); }
 <button>click</button> <button>click</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.

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