我有一个变量,我在其中动态填充图像位置。
我需要用该变量更改背景图像。我无法找到办法做到这一点。
var myImg = '/images/example1.jpg';
document.body.style.background = "url(myImg) no-repeat";
这似乎不起作用。
是否存在语法问题,还是应该以不同的方式完成?
答案 0 :(得分:1)
myImg
是字符串中的字面值。使用串联来使用变量:
document.body.style.background = "url(" + myImg + ") no-repeat";
答案 1 :(得分:0)
我喜欢这样
var bodyStyle = document.body.style;
bodyStyle.backgroundImage ='url('+ yourImage +')';
bodyStyle.backgroundRepeat ='no-repeat'