鼠标点击控制div层展开收缩

这篇博客介绍了如何使用CSS动画来控制div元素的展开和收缩效果。通过动态设置class,结合点击事件改变div的class属性,并在CSS中定义相应动画实现平滑过渡。文章提到了三种判断方法,包括三目运算符、对象式判断和在computed中的判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

.展开收缩时使用的CSS动画完成的(此例子使用了第三种判断方法)

一.首先动态设置class:

1.三目运算符判断

<div class="hello" :class="isActive?'anmDiv':'aaa'"></div>

2.对象式判断

<div class="hello" :class="{ 'aaa': isActive, 'ccc': isSort }" />

3.在computed里面判断

     <div class="hello" :class="divStyle"></div>

<script>
export default {
  computed:{
      divStyle(){
        if(this.id===1) {
              return 'aaa'
        }else if(this.id===2){
              return 'ccc'
        }
     }
  },

二.在点击事件里设置改变div的class的属性及相应的操作

    changeWidth(){
      if(this.id===0 || this.id===2){
            this.id=1
      }else if(this.id===1){
            this.id = 2
      }
    }

三.在css里面设置动画

<style>
.hello{
width: 100px;
height: 200px;
background: #42b983;
}
.ccc{
transition: 3S;
}
.aaa{
width: 100%;
transition: 3S;
}
</style>

或者: 

<style>
.hello{
width: 100px;
height: 200px;
background: #42b983;
}
.ccc{
animation:myfirst1 3s;
-moz-animation:myfirst1 3s; /* Firefox */
-webkit-animation:myfirst1 3s; /* Safari and Chrome */
-o-animation:myfirst1 3s; /* Opera */
}
@keyframes myfirst1 {
  from {width:100%;}
to {width:100px;}
}
.aaa{
width: 100%;
animation:myfirst 3s;
-moz-animation:myfirst 3s; /* Firefox */
-webkit-animation:myfirst 3s; /* Safari and Chrome */
-o-animation:myfirst 3s; /* Opera */
}
@keyframes myfirst
{
from {width:100px;}
to {width:100%;}
}
</style>

完整代码:

<template>
  <div class="hello1">
     <div class="hello" :class="isActive?'anmDiv':'aaa'"></div>  
     <button @click="changeWidth">change</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
       isActive: true,
    }
  },
  methods:{
    changeWidth(){
       if (this.isActive) {
         this.isActive = false
       } else {
         this.isActive = true
       }
    }
  }
}
</script>
<style>
.hello{
width: 100px;
height: 200px;
background: #42b983;
}
.anmDiv{
transition: 3S;

}
.aaa{
width: 100%;
transition: 3S;
}
</style>

 

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值