css挂载动态样式,使用变量动态展示

本文介绍了如何在Vue或类似的框架中,通过CSS变量和三元表达式在HTML模板中动态挂载样式,包括使用class和style属性,以及如何结合SCSS进行样式定义。
摘要由CSDN通过智能技术生成

css挂载动态样式

<template>
  <!-- 方式1  这种暂时无法直接挂载style-->
  <div :class="{ myStyle: disabled }" />

  <!-- 方式2   class  style皆可-->
  <div :class="disabled ? 'myStyle' : 'myStyle2'" />
  <div :style="{ width: disabled ? '200px' : '300px' }" />
  
  <!-- 方式3 传递变量-->
  <div  :style="{ '--height': height + 'px', '--maxHeight': maxHeight + 'px'}"/>
</template>


<script>
  const disabled = true
</script>


<style scoped lang="scss">
  .myStyle {
    display: none;
    min-height: var(--height);
    max-height: var(--maxHeight);
  }
</style>

如代码所示, disabled是个布尔变量,只需要在style或者class前面加冒号:就可以使用变量,

1、 { class样式 : 变量xxx } ps:注意,需要多套一层大括号
2 、 使用三元表达式 变量xxx ? class样式a : class样式b

两种方法都可以,任选其一

  • 11
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值