JavaScript SetTimeout 更改背景颜色

JavaScript SetTimeout to change background color

本文关键字:背景 颜色 SetTimeout JavaScript      更新时间:2023-09-26

我正在尝试(但失败了)使用javascript来更改我正在构建的网页元素的背景颜色和不透明度。这是我的javascript文件中的代码。

setTimeout(function background() {
    document.body.style.backgroundColor = "#000";
},1000);

我不确定为什么这不起作用,如果有人能提供帮助,那就太神奇了。我也不知道如何使此功能在 1 秒后将图像的不透明度从 0 更改为 1,从 1 更改为 0。如果有人能伸出援手,那将是惊人的。

谢谢!

下面介绍如何设置背景颜色和不透明度,以及所有图像的不透明度。注意我使用了jQuery:

setTimeout(function background() {
    // How to set the background color and opacity? The last value is opacity
    document.body.style.backgroundColor = "rgba(0,0,0,0.5)";
    // How to set opacity for all images
    $('img').css('opacity', '1.0');
},1000);

为了仅使用JavaScript天真地更改图像的不透明度:

var images = document.getElementsByTagName('img'); 
for(var i = 0; i < images.length; i++) {
    images[i].style.opacity = '1.0'; // Or '0.0'
}

使用 RGBA 来影响背景颜色和不透明度

setTimeout(function background() {
    document.body.style.backgroundColor = "rgba(0,0,0,0.5)";
},1000);

这是小提琴

并检查不透明度和 RGBA