美文网首页
2021-08-11 Vue 利用css的var() 和attr

2021-08-11 Vue 利用css的var() 和attr

作者: 追寻1989 | 来源:发表于2021-08-11 15:08 被阅读0次

vue绑定style直接给css的var变量传递一个值,然后结合css的var()函数使用这个值。

在data里面定义一个变量然后给定一个值,后期修改这个值之后,所有依赖这个变量的css样式都会被响应式地修改。css用var()函数来使用这个变量,变量前要加--

代码演示:

<div id="app">
    <div class="header" :style="{'--heightVar': heightVal}">header</div>
    <div class="body">body</div>
    <div class="footer" :style="{'--heightVar': heightVal}">footer</div>
</div>
<script type="text/javascript">
    let vm = new Vue({
        el: '#app',
        data: () => {
            return {
                heightVal: '50px'
            }
        }
    })
</script>
<style type="text/css">
    .header,
    .footer {
        background: rgb(53, 122, 187);
    }

    .body {
        height: 150px;
        background: rgb(37, 205, 218);
    }

    .header {
        height: var(--heightVar);
    }

    .footer {
        height: var(--heightVar);
    }
</style>

在浏览器中演示:


页脚和头部的height css样式都使用了--heightVar变量,而它的值又是Vue的heightVal传来的,所以当修改heightVal的值之后所有依赖于--heightVar变量的css样式都会被修改。

补充:
针对伪元素的content使用var()函数动态改变无效,需要使用attr()函数

总结:
var()函数必须要获取内联属性, 即必须要是在style中的属性
attr()函数需要获取的标签中的属性, 也可以是自定义属性, 但是必须要是在标签中的属性

再补充个更容易理解的案例:

<template>
  <div id="app">
    <span :style="spanStyle" class="span1">hello world</span>
    <br />
    <span
      :style="{ '--width': widthVar }"
      :content = "contentVar"
      class="span2"
      >hello earth</span
    >
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      spanStyle: {
        "--color": "red",
      },
      widthVar: "150px",
      contentVar: "你好",
    };
  },
};
</script>

<style>
.span1 {
  color: var(--color);
}
.span2 {
  text-align: center;
  position: relative;
  width: var(--width);
  --colorTest: skyBlue; // var变量也可以在这里使用和定义
}
.span2::after {
  content: attr(content);
  background-color: var(--colorTest);
  display: block;
  position: absolute;
  left: 100%;
  width: var(--width);
  height: var(--width);
  border-radius: 50%;
  border: 2px solid black;
}
</style>
执行效果

参考文献:https://www.cnblogs.com/longxingzhe/p/14397976.html

相关文章

网友评论

      本文标题:2021-08-11 Vue 利用css的var() 和attr

      本文链接:https://www.haomeiwen.com/subject/tercbltx.html