CSS自定义属性(CSS变量)

来源:互联网 发布:桌面快速启动软件 编辑:程序博客网 时间:2024/06/05 05:06

除了sass,less等预编译器外,css自身也支持定义变量

html

<section>      <i></i>      <div>           test test test test test test test test test test test test test test test test test test test test test      </div></section><div id="test">    <div id="test__title">font-size:28px</div></div>

css

/*全局变量*/:root {    --bgcolor: yellow;    --sec-color:blue;    --font-size:22px;    --quanjv:1;        /*[JS] getComputedStyle(document.body).getPropertyValue('--quanjv')//'1'   */}section {    background: var(--bgcolor);/*取--bgcolor的值*/    color:var(--sec-color,blue);/*取--sec-color的值,如果没有,则使用默认值(blue)*/    --multy:20;    width: calc(var(--font-size) * var(--multy)*1.1);/*多个变量计算*/}section:after{    content: '';    display: block;    clear: both;}section i {    width: 100px;    height: 100px;    background: currentColor;/*使用默认颜色,取color的值,没定义取父元素的color*/    display: inline-block;    float: left;    border-radius: 50%;    shape-outside: circle();    margin: 10px;}/*局部变量*/section div {    word-break: break-all;    font-size:var(--font-size,14px);/*找不到该变量,不在变量的作用域,使用默认值14px*/}#test__title{    font-size:var(--font-size,10px);/*使用局部变量,在下方*/}#test{    --font-size:28px;/*定义局部变量*/    --jubu:2;    /*[JS]  getComputedStyle(document.body).getPropertyValue('--quanjv')    =  ''  ,无法获取;    getComputedStyle(document.getElementById('test')).getPropertyValue('--jubu')    =   "2"    */}@supports(--a:0){    /*支持*/}@supports(not(--a:0)){    /*不支持*/}

还可以JS操作

//改变变量document.documentElement.style.setProperty('--sec-color','red');//JS操作//获得变量getComputedStyle(document.body).getPropertyValue('--quanjv');//1//获取支持性if(window.CSS&&window.CSS.supports&&window.CSS.supports('--a',0)){       console.log('support')   }else{       console.error('not support')  }

img

0 0
原创粉丝点击