2016-06-15 46 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