background和background-image的区别

原文出处:https://blog.csdn.net/zfz5720/article/details/80065047

我们在使用背景图时,通常会用到background. 
今天遇到一个这样的问题,在vue项目中,给一个按钮加了一张背景图片,用的是background,大小用的contain。现在有一个需求,当点击按钮时,按钮的背景图片需要切换。问题来了,换是换了,但是背景的大小却失效了。 
代码如下:

 <button :style="{background: stop}" style="background-size:contain;width: 40px; height: 40px;></button>

为什么呢? 

之所以这样,是因为background是一个集合,它包括background-color,background-image,background-size等等, 
当你改变background时,他会把你之前的background下的子样式覆盖,

    this.$refs.btnBg.style.background = this.stop;      

你换了背景之后,之前的background-size就不起作用了。 
所以解决办法:用background-image,

<button :style="{backgroundImage: stop}" style="background-size:contain;background-color: rgb(35, 39, 49);"></button>

 this.$refs.btnBg.style.backgroundImage = this.stop;

这样就不会出现样式覆盖了,还有一点就是,使用background-image,带有透明的png,透明部分不会显示透明,你需要设置background-color
 

猜你喜欢

转载自blog.csdn.net/chelen_jak/article/details/84333442