2017-07-06 41 views
0

我的代碼有什麼問題?出於某種原因,我的函數load()不會改變.firstDiv背景?背景不改變onclick功能

我找不到任何錯誤。

function load() { 
 
document.getElementsByClassName("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')"; 
 
}
.firstDiv, .secondDiv { 
 
    width: 50%; 
 
    height:100vh; 
 
    float: left; 
 
} 
 

 
.firstDiv { 
 
    background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg"); 
 
    background-position: center; 
 
    background-size: cover; 
 
    background-repeat: no-repeat; 
 
    box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2); 
 
    }
<div class="firstDiv"></div> 
 

 
<div class="secondDiv"> 
 
    <button onclick="load()">Change background</button> 
 
</div>

+0

非常感謝幫助。不知道。所以一般情況下最好使用id? – CaL17

+0

這取決於用例。將ID用於多個元素的唯一元素和類。 –

回答

1

你的問題是在這條線:

document.getElementsByClassName("firstDiv")... 

getElementsByClassName返回的HTMLCollection像報道在doc 。

您需要更改該行以:

document.getElementsByClassName("firstDiv")[0] 

的片段:

function load() { 
 
    document.getElementsByClassName('firstDiv')[0].style.backgroundImage 
 
= "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')"; 
 
}
.firstDiv, .secondDiv { 
 
    width: 50%; 
 
    height:100vh; 
 
    float: left; 
 
} 
 

 
.firstDiv { 
 
    background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg"); 
 
    background-position: center; 
 
    background-size: cover; 
 
    background-repeat: no-repeat; 
 
    box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2); 
 
}
<div class="firstDiv"></div> 
 
<div class="firstDiv"></div> 
 

 
<div class="secondDiv"> 
 
    <button onclick="load()">Change background</button> 
 
</div>

1

load()功能,需要以便它使用的getElementsByClassName第一元件,因爲它返回多個元件,以改變它。

document.getElementsByClassName("firstDiv")[0]... 
1

如果您正在使用getElementByClassName那麼你需要通過指定索引像[0]或可選擇地使用id

實例與類的名稱,指定項目編號:

function load() { 
 
document.getElementsByClassName("firstDiv")[0].style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')"; 
 
}
.firstDiv, .secondDiv { 
 
    width: 50%; 
 
    height:100vh; 
 
    float: left; 
 
} 
 

 
.firstDiv { 
 
    background-image: url("https://static.pexels.com/photos/200303/pexels-photo-200303.jpeg"); 
 
    background-position: center; 
 
    background-size: cover; 
 
    background-repeat: no-repeat; 
 
    box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2); 
 
    }
<div class="firstDiv"></div> 
 

 
<div class="secondDiv"> 
 
    <button onclick="load()">Change background</button> 
 
</div>

ID

  1. 分配ID如<div id="firstDiv"></div>
  2. JS代碼:

    document.getElementById("firstDiv").style.backgroundImage = "url('https://static.pexels.com/photos/140945/pexels-photo-140945.jpeg')";