用JS设置div的背景图问题

在css里面将div的background-size: cover;
背景图比div小。
背景图片会被放大充满,用JS改变div的背景图片
obj.style.background="url(xxxxx)"
之后,size:cover就失效了,图片被平铺重复显示了,求解?

background是全局的背景设置,例如

body {
    background: #fff url('xxx.png') no-repeat
}

拆分出来就是

body {
    background-color: #fff;
    background-image: url('xxx.png');
    background-repeat: no-repeat;
}

你设置了obj.style.background就覆盖了background-image,所以你要改成这样

obj.style.backgroundImage = 'url("xxx.png")'

温馨提示:答案为网友推荐,仅供参考
相似回答