vue前端给css样式类绑定动态值
- 第一种通过document.querySelector获取样式名
存在多个重复样式名时,querySelector仅匹配第一个
指定一个或多个匹配元素的 CSS 选择器。 可以使用它们的 id, 类, 类型, 属性, 属性值等来选取元素
var root = document.querySelector(':root');
root.setAttribute('style', '--speed: 60s');
- 第二种通过document.documentElement.style.setProperty设置对应变量
document.documentElement.style.setProperty('--speed', '60s')
以上两种实现效果等价,以下为完整使用代码
变量–speed其实你只需要把它们理解成 css 自定义属性看待,它们与 color、font-size 等正式属性没有什么不同
为什么选择两根连词线(–)表示变量?因为 $foo 被 Sass 用掉了,@foo 被 Less 用掉了。为了不产生冲突,官方的 CSS 变量就改用两根连词线了。
在 CSS 变量命名中,可以是中文,日文或者韩文,并没有过多的限制
<template>
<div class="pie">
<div class="pie1"></div>
<div class="pie2"></div>
</div>
</template>
<script>
onMounted(()=>{
// var root = document.querySelector(':root');
// root.setAttribute('style', '--speed: 60s');
document.documentElement.style.setProperty('--speed', '60s')
})
</script>
<style scoped lang="less">
:root {
--speed: 5s;
}
.pie {
width: 100px;
height: 100px;
background: #1890ff;
border-radius: 50%;
position: relative;
box-shadow: 0 0 4px 4px rgba(190, 199, 211, 0.48);
}
.pie1 {
position: absolute;
width: 100px;
height: 50px;
background-color: #e1fae4;
border-radius: 50px 50px 0 0;
transform: rotate(270deg);
transform-origin: 50px 50px;
}
.pie2 {
position: absolute;
width: 100px;
height: 50px;
background-color: #e1fae4;
border-radius: 50px 50px 0 0;
transform-origin: 50px 50px;
animation: rotated var(--speed) linear infinite;
}
@keyframes rotated {
0%{
transform: rotate(90deg);
background-color: #e1fae4;
}
50% {
transform: rotate(270deg);
background-color: #e1fae4;
}
50.0001% {
transform: rotate(-270deg);
background-color: #1890ff;
}
100% {
transform: rotate(-90deg);
background-color: #1890ff;
}
}
</style>