不透明度样式在回调 Java 脚本中不起作用?

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

在分配的事件侦听器函数 fade() 回调后,循环工作正常,但控制台显示不透明度在值更改时不会修改。我做错了什么?

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);
    }    
}

你的循环同步运行,浏览器 batches 样式改变 - 只有所有 Javascript 完成后显示才会更新,到那时,不透明度将回到 1,所以在视觉上,似乎没有任何变化。

改为在循环内添加一个小的延迟:

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>

(请注意,名为 element 的变量可能 实际上是一个元素 ,否则您很可能会给阅读代码的其他人造成混淆,包括稍后的您)

对于多个按钮,请确保声明 alpha 变量,否则它将隐式全局并由所有侦听器共享:

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>