CSS实现点击防抖

本文介绍了如何使用CSS实现点击节流功能,避免JavaScript中的函数频繁调用,通过在el-button组件中设置CSS动画来控制N秒内禁止点击,提供了一种简单易用的解决方案。

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

大家都知道,函数节流(throttle)是 JS 中一个非常常见的优化手段,可以有效的避免函数过于频繁的执行。但是,我今天确新学了一招CSS实现点击节流,分享给大家~

1. 实现背景

基于el-button封装的一个按钮组件,用法同Element

2. 实现原理

通过CSS,点击后设置N秒禁止点击的动画。

3. 优点

无需变量控制按钮状态,开箱即用。

4. 代码实现
<template>
  <el-button :class="{throttle: firstAddThrottle}" :circle="circle" :disabled="disabled" :icon="icon" :loading="loading" :plain="plain" :round="round" :size="size" :type="type"
             :style="cssVars" class="my-button" @click="handleClick"
  >
    <slot></slot>
  </el-button>
</template>

<script>
export default {
  name: 'Button',
  props: {
    // 尺寸 medium / small / mini
    size: {
      type: String,
      default: ''
    },
    // 类型		primary / success / warning / danger / info / text
    type: {
      type: String,
      default: ''
    },
    // 是否朴素按钮
    plain: {
      type: Boolean,
      default: false
    },
    // 是否圆角按钮
    round: {
      type: Boolean,
      default: false
    },
    // 是否圆形按钮
    circle: {
      type: Boolean,
      default: false
    },
    // 是否禁用状态
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否加载中状态
    loading: {
      type: Boolean,
      default: false
    },
    // 图标类名
    icon: {
      type: String,
      default: ''
    },
    //   节流秒
    second: {
      type: Number,
      default: 5
    }
  },
  computed: {
    cssVars() {
      return {
        '--throttleNum': this.second + 's'
      }
    }
  },
  data() {
    return {
      // 第一次点击的后添加节流,后面不需要了
      firstAddThrottle: false
    }
  },
  methods: {
    handleClick() {
      this.firstAddThrottle = true
      this.$emit('click')
    }
  }
}
</script>

<style lang="scss" scoped>
button {
  cursor: pointer;
}

.throttle {
  animation: throttle var(--throttleNum) step-end forwards;
}

button:active {
  animation: none;
}

@keyframes throttle {
  from {
    pointer-events: none;
  }
  to {
    pointer-events: all;
  }
}

</style>
5. 使用方式
  1. 引入组件(全局或局部引入)
  2. 使用
      <Button icon="el-icon-download" :second="3" size="mini" type="warning"  @click="exportClick">导出</Button > 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值