【实战】vue中css3的var()插入变量函数与JS变量结合实现动态CSS样式

  • 原创
  • 作者:程序员三丰
  • 发布时间:2024-06-21 08:18
  • 浏览量:647
本文以一个简单代码实战来学习一下CSS3中变量的使用,以及var()函数的应用。同时,结合JS代码实现了动态设置CSS的变量,更接近平时实际的代码开发。

先了解一下 css3 的 var() 函数

var() 函数用于插入 CSS 变量的值。

var() 函数的语法:

var(name, value)

name:必需。变量名(必须以两个破折号(—)开头,且区分大小写)。
value:可选。回退值(在未找到变量时使用)。

示例代码片段:

/* 定义变量 */
body{
  --fontSize: 18px;
  --color: #000000;
}

/* 使用变量 */
div-name{
  font-size : var(--fontSize);
  color: var(--color);
}

最终要实现效果

vue2 实现版本

<template>
  <div style="display: flex; justify-content: center;">
    <span v-for="item in list" :style="{'--text': item.text, '--color': item.color}"></span>
  </div>
</template>

<script>
  export default {
    name: '',
    components: {},
    props: {},
    data() {
      return {
        list: [
          { text: '"中"', color: 'red' },
          { text: '"华"', color: 'orange' },
          { text: '"人"', color: 'yellow' },
          { text: '"民"', color: 'orange' },
          { text: '"共"', color: 'green' },
          { text: '"和"', color: 'cyan' },
          { text: '"国"', color: 'blue' }
        ]
      };
    }
  };
</script>

<style lang="scss" scoped>
  span::after {
    content: var(--text);
    background-color: var(--color);
  }
</style>

uni-app (vue3)实现版本

<template>
    <view style="display: flex; justify-content: center;">
        <view v-for="(item, index) in list" :style="{'--text': item.text, '--color': item.color}" :key="index"
            class="text-item">
        </view>
    </view>
</template>

<script setup>
    const list = [{
            text: '"中"',
            color: 'red'
        },
        {
            text: '"华"',
            color: 'orange'
        },
        {
            text: '"人"',
            color: 'yellow'
        },
        {
            text: '"民"',
            color: 'orange'
        },
        {
            text: '"共"',
            color: 'green'
        },
        {
            text: '"和"',
            color: 'cyan'
        },
        {
            text: '"国"',
            color: 'blue'
        }
    ]
</script>

<style lang="scss" scoped>
    .text-item::after {
        font-size: 60px;
        content: var(--text);
        background-color: var(--color);
    }
</style>
声明:本文为原创文章,51blog.xyz和作者拥有版权,如需转载,请注明来源于51blog.xyz并保留原文链接:https://mp.51blog.xyz/article/62.html

文章归档

推荐文章

buildadmin logo
Thinkphp8 Vue3 Element PLus TypeScript Vite Pinia

🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。

热门标签

PHP ThinkPHP ThinkPHP5.1 Go Mysql Mysql5.7 Redis Linux CentOS7 Git HTML CSS CSS3 Javascript JQuery Vue LayUI VMware Uniapp 微信小程序 docker wiki Confluence7 学习笔记 uView ES6 Ant Design Pro of Vue React ThinkPHP6.0 chrome 扩展 翻译工具 Nuxt SSR 服务端渲染 scrollreveal.js ThinkPHP8.0 Mac webman 跨域CORS vscode GitHub ECharts Canvas