如何确保可视化是通过javascript随css更改而更新的



示例。。

<input type="button" value="click me" id="p1">
<script>
document.querySelector("#p1").onclick = function () {
this.style.backgroundColor = "green";
alert(`My background color is ${this.style.backgroundColor} ??`);
}
</script>

警报文字我的背景颜色是绿色,但在警报时刻,颜色是灰色!!

我知道很多方法可以解决这个问题:

  • 不使用alert,而是显示div
  • 使用setTimeout
  • 将sleep函数与async await一起使用(sleep()的JavaScript版本是什么?)

。。但是有没有一种方法可以确保浏览器渲染完成?

您可以使用requestAnimationFrame-类似于setTimeout,只是浏览器会在重新绘制之前处理函数的运行时间。

一个简单的例子:

function tellMe() {
alert(`My background color is ${document.querySelector('#p1').style.backgroundColor} ??`);
}
document.querySelector("#p1").onclick = function() {
this.style.backgroundColor = "green";
requestAnimationFrame(function() {
requestAnimationFrame(tellMe)
});
}
<input type="button" value="click me" id="p1">