Backgroundimg url 不随 javascript 改变

Backgroundimg url not changing with javascript

window.onload = myFunction;

function myFunction() {

  document.getElementById('banner').style.backgroundImage = "url (../img/Background2.jpg)";

//这个函数是改变启动时的背景 }

#banner {
  background-image: url(../img/Background2.jpg);
}
<div id="banner">

您的问题是 JS 中 url( 之间的 space。

所以行:

document.getElementById('banner').style.backgroundImage = "url (../img/fff.png)";

需要成为:

document.getElementById('banner').style.backgroundImage = "url(../img/fff.png)";

这是一个工作示例:

window.onload = myFunction;

function myFunction() {

  document.getElementById('banner').style.backgroundImage = "url(https://via.placeholder.com/350x350)";

//This function is to change the backgroundimg on launch
}
#banner {
  width: 500px;
  height: 500px;
  background-image: url('https://via.placeholder.com/350x150');
}
<div id="banner"></div>