简体   繁体   English

如何在JavaScript中制作背景数组

[英]How do you make a background Array in javascript

I am trying to make an array of images so that my full page background can switch between the images in my array I have the Id on my html tag the image is being applied via CSS and I want the image to cycle through my array of images. 我正在尝试制作一个图像数组,以便我的整个页面背景可以在我的数组图像之间切换。我的html标签上有ID,该图像是通过CSS应用的,我希望该图像在我的图像数组中循环。

The code I have so far. 我到目前为止的代码。 Right my code change my whole page to the string of the location of the files for the images I want the background image to change not have my whole page turn white with some text at the top. 正确,我的代码将整个页面更改为图像的文件位置的字符串,我想要更改背景图像,而不是整个页面都变成白色,顶部带有一些文本。

any help would be great. 任何帮助都会很棒。

 var backgroundArray = ["../images/video.jpg", "../images/stars2.jpg", "../images/junkyard.jpg"]; var bgIndex = 0; function changeBackground(){ var newBg = backgroundArray[bgIndex]; var mainBg = document.getElementById('html'); mainBg.innerHTML = newBg; bgIndex++; if (bgIndex > backgroundArray.length-1){ bgIndex = 0; } } 
 html background: url(../images/video.jpg) no-repeat 0 top fixed; background-size: cover; 
 doctype html(lang="en" id="html") head 

You are setting innerHTML which does replace the content of the page. 您正在设置innerHTML ,它不会替换页面的内容。 If you want to change the background, use the style object on the element: 如果要更改背景,请在元素上使用style对象:

mainBg.style.backgroundImage = 'url(' + newBg + ')';

You are basically creating a CSS rule, just as you would in a stylesheet, but building it in the string instead. 基本上,就像在样式表中一样,您正在创建CSS规则,而是在字符串中构建它。

Use 采用

document.body.style.backgroundImage = "url('" + newBg + "')"

instead of 代替

var mainBg = document.getElementById('html');
    mainBg.innerHTML = newBg;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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