在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 @ 2023-01-11 10:27  当下是吾  阅读(915)  评论(0编辑  收藏  举报