css的原生变量&css的各种操作小技巧

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

记录日常css变量的一些使用技巧, 方便在自己忘记时,及时查阅.


一、原生css变量

1、基础用法

定义变量使用 “–” + 变量名
css变量具有作用域, 子元素只能使用父级元素内定义的css变量
想要定义全局变量, 可以在:root下进行定义

<body>
	<div class="test"></div>
	<div class="test_1">
		<div class="test_1_1"></div>
	</div>
	<div class="test_2">
		<div class="test_2_1"></div>
	</div>
</body>

<style>
:root{
	--width:200px;
	--height:200px;
	--color:red;
}

.test{
	height:var(--height);
	width:var(--width);
	background-color:var(--color)
}

.test_1{
	--color1:blue;
}

.test_1_1{
	height:var(--height);
	width:var(--width);
	background-color:var(--color1)
}

.test_2_1{
	height:var(--height);
	width:var(--width);
	background-color:var(--color1) // 无效,不在css变量的作用域内
}
</style>

2、js定义css变量/行内定义变量

<body>
	<style>
	    .test_1 {
	      width: 200px;
	      height: 200px;
	      background-color: var(--color)
	    }
		.test_2{
		  width:200px;
		  height:200px;
		  background-color:var(--color1);
		}
  	</style>
  	
  	<!-- js定义 -->
	<div class="test">
	  <div class="test_1"></div>
	</div>
	
	<!-- 行内定义 -->
	<div class="test1" style="--color1: blue">
	  <div class="test_2"></div>
	</div>

	<script>
	  var div = document.querySelector('.test');
	  div.style.cssText = '--color:red'
	</script>
</body>
注意

div.style.cssText会覆盖行内样式, 所以不能和行内同时使用

二、css3的currentColor关键字

可以指代最近的父级的color. 如果你使用过antd的icon组件,一定知道, icon的颜色取决于父级的color颜色. 明明是svg的fill属性填充的颜色,为什么会使用到父级的color呢? 原因就是使用了currentColor

<body>
  <style>
    .test {
      color: blue;
    }

    .test_1 {
      width: 200px;
      height: 200px;
      background-color: currentColor;
    }
  </style>
  <div class="test">
      <div class="test_1"></div>
  </div>
</body>

三、通过dom自定义属性, 替换伪元素内容

正常使用伪元素

<body>
  <style>
    .test::after {
      content: 'test';
      color: blue;
    }
  </style>
  <div class="test"></div>
</body>

这样的使用方式, 能用到的场景实在有限, 大部分的业务场景要求content的内容是动态的,写死在css中,将没有意义. 但是如何使用js来控制content的内容呢?

js替换伪元素内容

答案是利用dom的自定义属性来做. 这里也将要使用要一个新的css函数

<body>
  <style>
    .test::after {
      content: attr(data-hint);
      color: blue;
    }
  </style>
  <div class="test" data-hint="不知名前端"></div>

   <script>
    window.document.documentElement.onclick = () => {
      var target = document.querySelector('.test')
      target.setAttribute('data-hint', '不知名前端-不知名')
    }
  </script>
</body>

刷新页面后, 点击任意位置, 看到了什么?

总结

本着能用css, 绝不动用js的原则, 学会css的各种奇淫巧技还是有比较的哇

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值