我正在尝试让背景图像交替。它以前是工作的,但现在有些东西已经关闭了。现在背景与 CSS 设置的相同,我想更改它以替换它。
var widthOfBrowser = window.innerWidth;
var heightOfBrowser = window.innerHeight;
var hideImage;
var timeInterval = 20000;
var time = 5000;
var changeNavBar = document.getElementsByTagName("body")[0];
var T1;
var T2;
var T3;
var intervalMain;
var text;
var parent;
var child1;
var child2;
var valueHidePadding;
var mobileTwo;
var desktopView;
var obj3;
var obj1;
var obj2;
if (widthOfBrowser < 500) {
hideImage = document.getElementsByTagName("body")[0];
hideImage.style.backgroundImage = "url('')";
parent = document.getElementById("parent");
child1 = document.getElementById("removeMobile1");
child2 = document.getElementById("removeMobile2");
parent.removeChild(child1);
parent.removeChild(child2);
} else {
intervalMain = setInterval(function() {
putTogether()
}, timeInterval);
function putTogether() {
T1 = setTimeout(function() {
image1()
}, time); //after 5 seconds the function alternatingImages1to2 will be executed
time += 5000;
T2 = setTimeout(function() {
image2()
}, time); //after 10 seconds the function alternatingImages2to3 will be executed
time += 10000;
T3 = setTimeout(function() {
image3()
}, time);
time = 5000;
}
}
function image1() {
obj1 = document.getElementsByTagName("body")[0];
obj1 = obj1.style.backgroundImage = "url('')";
}
function image2() {
obj2 = document.getElementsByTagName("body")[0];
obj2 = obj2.style.backgroundImage = "url('')"; //placeholder img
}
function image3() {
obj3 = document.getElementsByTagName("body")[0];
obj3 = obj3.style.backgroundImage = "url('')"; //placeholder image
}
// Related css
body {
background: url("https://c1.staticflickr.com/1/126/387606063_408c203f6c_b.jpg") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
/* This is to set the background */
}
最佳答案
您好像忘了添加图片网址:
obj1.style.backgroundImage = "url('')"
应该是:
obj1.style.backgroundImage = "url('path/to/image.jpg')"
关于JavaScript 尝试替换 backgroundImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367065/