是否可以使用javascript同时设置背景和背景图像?

时间:2016-06-15 01:48:27

标签: javascript css

每当我尝试通过javascript设置background和background-image属性时,我只会在元素上获得背景peroperty。为什么会这样?我错过了什么吗?

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

// only gets..

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

2 个答案:

答案 0 :(得分:5)

您可以在一个语句中设置多个背景

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

在您的代码中,您将一个背景与另一个背景重叠,因为backgroundbackground-image css属性都可以设置背景图像。

答案 1 :(得分:5)

可以在backgroundImage属性设置多个style。您可以使用backgroundPosition调整图片位置,以显示多个backgroundImage

&#13;
&#13;
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";
&#13;
div {
  width:100px;
  height:50px;
  background-repeat:no-repeat;
}
&#13;
<div></div>
&#13;
&#13;
&#13;

相关问题