在vue中使用CSS变量

首先,我们要先知道什么是CSS变量,可以先看这篇文章
在我们知道什么是CSS变量之后,我们尝试把它在项目中运用起来,一些需要动态计算的值,我们就可以使用它快速的实现效果。

以下为示例一,其中keyframes是不能直接在html中书写的,那么如何不使用js就能根据传入的值达到对应的效果呢?如下:

复制代码
<template>
  <div
    :style="{ '--deviation': '-' + deviation }"
    class="text"
  >
    {{ text }}
  </div>
</template>

<script>
export default {
    name: 'QTest',
    props: {
        text: {
            type: String,
            default: '请传入内容'
        },
        // 动态传入不同的值,根据不同的值得出最终的样式
        deviation: {
            type: String,
            default: '75%'
        }
    },
}
</script>

<style lang="scss" scoped>
.text {
    width: 100px;
    overflow: hidden;
    transition-delay: 5s;
    animation: itemSlide 5s linear infinite;
}

@keyframes itemSlide {
    0% {
        transform: translateX(0%);
    }

    100% {
        /*使用变量*/
        transform: translateX(var(--deviation));
    }
}
</style>
复制代码

以下为示例二,有的时候,一些属性我们可能需要根据一些条件计算得来,那么也能很好的去使用它。如下:

复制代码
<template>
  <div
    :style="{ '--lineheight': lineheight }"
    class="text"
  >
    <div class="container"></div>
  </div>
</template>

<script>
export default {
    name: 'QTest',
    props: {
        lineheight: {
            type: String,
            default: '200px'
        }
    },
}
</script>

<style lang="scss" scoped>
.text {
    width: 100px;
    height: 400px;
    overflow: hidden;

    .container {
        height: calc(100% - var(--lineheight));
        background-color: red;
    }
}
</style>
复制代码

就得到一个高度为200px的盒子:

 

 补充:
获取元素样式:getComputedStyle([el]

const styles = getComputedStyle(document.documentElement)
const value = String(styles.getPropertyValue('--lineheight')).trim()

 

原文

posted @   当下是吾  阅读(1092)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示