【发布时间】:2021-10-13 22:41:42
【问题描述】:
我正在尝试让我的网站的背景图片每隔一定的秒数改变一次,我尝试这样做:
var images = new Array(
'Space.gif',
'Windows.gif',
);
var slider = setInterval(function() {
document.getElementsByClassName('bg-img')[0].setAttribute('style', 'background-image: url("'+images[0]+'")');
images.splice(images.length, 0, images[0]);
images.splice(0, 1);
}, 10000);
body {
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: 100%;
}
<div class="bg-img" style="background-image: url('space.gif'),background-image: url('windows.gif');">
<div class="overlay"></div>
</div>
我也尝试过使用这段 JavaScript 代码:
function changeBg(){
const images = [
'url("Space.gif")',
'url("Windows.gif")',
]
const selection = document.querySelector('selection')
const bg = images[Math.floor(Math.random()* images.length)];
selection.style.backgroundImage = bg;
}
setInterval(changeBg, 1000000)
但没有任何效果:(
【问题讨论】:
-
在您的 CSS 中,您正在为背景图像准备
<body>。但是您的 JavaScript 引用了.bg-img元素。要将背景图像应用到<body>还是<div>?此外,如果<div>没有宽度或高度,它可能不会显示在页面上。 -
我正在尝试将背景更改为整页,所以这意味着我必须在 css 中更改“bg-img”的“body”对吗?
-
为什么不能改错字??
-
我可以修正缺少引号的错字,但我的页面仍然没有改变背景图片:/
标签: javascript html css image background