2016-06-15 76 views
2

每當我嘗試通過javascript設置背景和背景圖像屬性,我只會獲取元素的背景屬性。這是爲什麼發生?我錯過了什麼?是否可以使用javascript同時設置背景和背景圖像?

divelement.style.background = "url('one.png')" 
divelement.style.backgroundImage = "url('two.png')" 

// only gets.. 

<div style="background-image: url("one.png");"> 
+1

應該如何顯示的兩個背景圖像的更多?在相同的位置? – guest271314

+1

這是因爲'背景'是一個短手屬性,它也設置'background-image'因此覆蓋它 – LGSon

+0

@LGSon完美的解釋:)即將發佈相同的東西。 – www139

回答

5

可以設置多背景在一條語句:

divelement.style.background = "url('one.png'), url('two.png')"; 

在你的代碼,你將覆蓋一個背景,其他的,既backgroundbackground-image CSS屬性可以設置背景圖片。

5

可以設置多個backgroundImagestyle屬性。您可以使用backgroundPosition調整圖像位置,以顯示比單backgroundImage

var div = document.querySelector("div"); 
 
div.style.backgroundImage = "url(http://lorempixel.com/50/50/technics),\ 
 
    url(http://lorempixel.com/50/50/nature)"; 
 
div.style.backgroundPosition = "0px 0px, 50px 0px";
div { 
 
    width:100px; 
 
    height:50px; 
 
    background-repeat:no-repeat; 
 
}
<div></div>

+0

很好的辯論答案:) – christian

+0

或者你可以使用透明圖像 – Kaiido

+0

在一個'div'元素上使用'backgroundPosition'的四個背景圖片https://jsfiddle.net/bb8gt9x1/ – guest271314