IT俱乐部 CSS 前端 CSS 动态设置样式::class、:style 等技巧(推荐)

前端 CSS 动态设置样式::class、:style 等技巧(推荐)

一、:class 动态绑定类名

v-bind:class(缩写为 :class)可以动态地绑定一个或多个 CSS 类名。

1. 对象语法

通过对象语法,可以根据条件动态切换类名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div>海绵宝宝不喜欢侬,喜欢章鱼哥。</div>
 
export default {
  data() {
    return {
      isActive: true,
      hasError: false,
    };
  },
};
 
.greenText {
  color: green;
}
.red-text {
  color: red;
}
  • greenText:当 isActive 为 true 时,添加 greenText 类。
  • red-text:当 hasError 为 true 时,添加 red-text 类。

效果图:

2. 数组语法

通过数组语法,可以同时绑定多个类名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div>海绵宝宝不喜欢侬,喜欢章鱼哥。</div>
 
export default {
  data() {
    return {
      textClass: 'greenText',
      bgcClass: 'pinkBgc',
    };
  },
};
 
.greenText {
  color: green;
}
.pinkBgc {
  width: 300px;
  height: 200px;
  background-color: pink;
  margin: 200px auto;
}

textClass 和 bgcClass 是数据属性,它们的值会同时作为类名绑定到元素上。

效果图:

3. 结合计算属性

当类名的逻辑较为复杂时,可以使用计算属性来动态生成类名对象。

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
<div>海绵宝宝不喜欢侬,喜欢章鱼哥。</div>
 
export default {
  data() {
    return {
      isActive: true,
      hasError: true
    };
  },
  computed: {
    computedClass() {
      return {
        greenText: this.isActive && !this.hasError,
        'text-red': this.hasError
      };
    }
  }
};
 
.greenText {
  color: green;
}
.text-red{
  color: red;
}
  • greenText:isActive 为true并且hasError为false的时候生效;
  • text-red:hasError 为true的时候生效;

效果图:

二、:style 动态绑定内联样式

v-bind:style(缩写为 :style)可以动态地绑定内联样式。

1. 对象语法

通过对象语法,可以直接绑定样式对象。

1
2
3
4
5
6
7
8
9
10
<div>海绵宝宝不喜欢侬,喜欢章鱼哥。</div>
 
export default {
  data() {
    return {
      activeColor: 'red',
      fontSize: 12
    };
  },
};

activeColor 和 fontSize 是数据属性,它们的值会作为样式绑定到元素上。
效果图:

2. 数组语法

通过数组语法,可以同时绑定多个样式对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div>海绵宝宝不喜欢侬,喜欢章鱼哥。</div>
 
export default {
  data() {
    return {
      styles1: {
        color: 'red',
        fontSize: '14px'
      },
      styles2: {
        fontWeight: 'bold',
        textDecoration: 'underline'
      }
    };
  },
};

styles1 和 styles2 的所有样式都会绑定到元素上。
效果图:

3. 使用三元表达式

可以在 :style 中使用三元表达式,根据条件动态设置样式值。

1
2
3
4
5
6
7
8
9
<div>海绵宝宝不喜欢侬,喜欢章鱼哥。</div>
 
export default {
  data() {
    return {
      isActive: true
    };
  },
};

效果图:

4. 使用模板字符串

可以使用模板字符串动态拼接样式值。

1
2
3
4
5
6
7
8
9
10
<div class="demo">海绵宝宝不喜欢侬,喜欢章鱼哥。</div>
 
export default {
  data() {
    return {
      isActive: false,
      fontSize: 12
    };
  },
};

效果图:

到此这篇关于前端 CSS 动态设置样式::class、:style 等技巧(推荐)的文章就介绍到这了,更多相关css动态设置样式内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章,希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/css/14718.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部