• vue使用CSS 变量


    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

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

    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    就得到一个高度为200px的盒子:
    在这里插入图片描述

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

    const styles = getComputedStyle(document.documentElement)
    const value = String(styles.getPropertyValue('--lineheight')).trim()
    
    • 1
    • 2
  • 相关阅读:
    【软件测试】01 -- 软件生命周期、软件开发模型
    Qt+FFmpeg+opengl从零制作视频播放器-12.界面美化
    【常用图像增强技术,Python-opencv】
    Obsidian+SyncTrayzor打造个人文档云同步平台
    【后端速成 Vue】初识指令(上)
    有趣的css样式
    『现学现忘』Docker基础 — 25、Docker镜像讲解
    【Linux】缓冲区
    Mysql详细安装步骤
    iOS端如何实现MobLink的场景还原功能
  • 原文地址:https://blog.csdn.net/qq_40864647/article/details/126162282