• css变量的声明和读取 吴小明


    1、css变量的声明

      使用--声明变量($被sass用掉了,@被less用掉了)

      <style>
        :root {
          --color: red;
        }
      </style>

      root为根元素,相当于给html设置了css变量

        /* :root 相当于 html */
        html {
          --color: red;
        }

    2、变量的读取

      通过val函数读取

        div {
          color: var(--color);
        }

      

      val函数第二个参数,可选值,当变量不存在时读取第二个值

       

    3、变量的类型

      ①当变量的类型为字符串时,可以与其他字符串拼接

        div::after {
          --text1: 'hello ';
          --text2: var(--text1) 'world';
          content: var(--text2, '萨瓦迪卡') '!'
        }

      

      ②当变量的类型为数字时,不能和单位直接拼接,需要用calc函数拼接

        div {
          color: var(--color, blue);
          --width: 50;
          width: calc(var(--width) * 1px);
          background-color: red;
        }

      

    4、变量的作用域

      变量的作用域就是它所在选择器的范围

      当作用域内有多个同名变量,按优先级最高的生效,同样式生效的规则一致

        

      全局的变量通常放在根元素:root里面,这样任何选择器都可以读取

    5、响应式布局

        <style>
          body {
            --primary: blue;
            --secondary: blue;
          }
          a {
            color: var(--primary);
            text-decoration-color: var(--secondary);
          }
          @media screen and (min- 350px) {
            body {
              --primary: red;
              --secondary: red;
            }
          }
        </style>
      </head>
      <body>
        <a href="">链接1</a>
        <a href="">链接2</a>
      </body>

      

      

    6、兼容性处理

          div{
            color: red;
            color: val(--color);
          }

    7、内联重新赋值css变量

      通过getComputedStyle(document.documentElement).getPropertyValue('--c-999')可以获取到html标签中定义的--c-999变量

      ①此时div的颜色为#999

      

      ②style属性中可以重新定义--c-999的颜色

      

    8、js操作

      ①通过setProperty设置css变量

      

      ②通过removeProperty删除css变量

      

      ③写一段在css中无用但在js中可以读取的代码

      <style>
        :root {
          --foo: if(x > 5) this.width = 10;
        }
      </style>
    </head>
    <body>
      <script>
        const res = getComputedStyle(document.documentElement).getPropertyValue('--foo')
        console.log(res.trim()) // if(x > 5) this.width = 10
      </script>
    </body>
  • 相关阅读:
    windows修改环境变量的工具—Rapid Environment Editor
    JS 实现文件夹目录选择
    nginx 反向代理
    centOS7安装nginx及nginx配置
    yum安装时出现:Cannot retrieve metalink for repository: epel. Please verify its path and try again
    关于 PGP 加密与签名相关整理
    使用flink和kafka实现端到端的Exactly Once语义
    基于php的Http请求类封装
    Golang获取客户端IP
    Golang生成唯一的GUID
  • 原文地址:https://www.cnblogs.com/wuqilang/p/16023515.html
Copyright © 2020-2023  润新知