动态style那点事

319 阅读1分钟

静态style中:

style="{backgroundSize:100%,100;marginLeft: 20px}"

style="{background-size:100%,100%;margin-left: 20px}" 等价

现象:行内样式中的backgroundSize会编译成css中的background-size属性

动态style中:

:style="{backgroundSize:'100%,100%',marginLeft: '20px'}"

:style="{'background-size':'100%,100%','margin-left': '20px'}" 等价

现象:因为backgroundSize是js中的变量,且与css中background-size有映射关系,所以才能等效

个人建议在动态style中,把属性名也用引号引起来,方便copy css的属性

有个注意点:

动态style中的属性值必须是字符串,而变量本质必须是对应的字符串的值,之所以属性名不加引号是css和js样式有映射关系,且用{}包裹及逗号,分隔 ,如果在动态style中的属性值不加引号vue会当成变量来处理

静态style中的属性值跟外部style中的写法一样,属性值不用加引号,且以分号;分隔

可以参考js原生用法:

ele.style.backgroundColor = 'red';
ele.style['backgroundColor'] = 'red';
ele.style['background-color'] = 'red';

举个例子:引入一个background-image

静态引入:

<div
  style="
    background: url('https://yuntop.oss-cn-hangzhou.aliyuncs.com/mini_zjsport_filehost/2022-01-23/471a0654a2234fb9b70678e521880524-file.jpg')
    // background: url(../../assets/logo.png) 显示不出来,写法有问题
    // background: require(url(../../assets/logo.png)) 显示不出来,写法有问题
      no-repeat;
    backgroundsize: 800% 100%;
    color: red;
    width: 200px;
    marginleft: 20px;
    height: 200px;
  "
>
</div>

在线图片地址没有问题,本地图片这样写只会解析成一个 background: url(../../assets/logo.png) 的字符串,一般来说加上require就行了,但静态style中好像不识别require这个方法,所以本地图片的背景最好统一也用动态引入,如下:

动态引入:

<div
  :style="{
    width: '200px',
    height: '200px',
    background: `url(${img}) no-repeat`, // 使用${}外面一定有个` `模板字符串,切记!!!!
    //同上 background: 'url('+img+') no-repeat'里面不能用双引号,结构是'valueA'+'valueB'拼接
    backgroundSize: '200%,100%',
  }"
></div>

变量是:img: require("../../assets/logo.png"),

两种写法,推荐es6中的模板语法