简单滑块验证逻辑

本文介绍了如何使用HTML、CSS和JavaScript在前端开发中创建一个可拖动的按钮组件,通过监听鼠标事件调整按钮位置,并保持在限定范围内。
摘要由CSDN通过智能技术生成

在这里插入图片描述

<template>
 <div class="list">
   <el-card style="margin-top: 20px">
     <div style="width: 300px;height: 240px;background: #1890ff;" class="btn boxbtn">
       <div style="width: 300px;height: 180px;background: red;position: relative;">
         <div style="background: #FFFFFF;position: absolute;width: 40px;height: 40px;top: 80px" :style="{left:p+'px'}"></div>
       </div>
       <div style="width: 100%;height: 60px;background: #cce581;display: flex;align-items: center;justify-content: center">
         <div class="boxbtn" style="height: 30px;background: #7b7e80;width: 280px;position: relative;">
           <div style="height: 30px;background: #4b21ff;position:absolute;" :style="{width:(left+10)+'px'}"></div>
           <div class="btn bx" style="width: 50px;height: 30px;background: white;position:absolute;user-select: none" :style="{left:left+'px'}" @mousedown="handleStartMove">| | |</div>
         </div>
       </div>
     </div>
   </el-card>

 </div>
</template>

<script>

export default{
  data(){
    return{
      left:10,
      startX:0,
      start:0,
      p:0
    }
  },
  created() {

  },
  methods:{
    handleStartMove(e) {
      //clientX是当前鼠标点击的位置
      this.startX = e.clientX;
      this.start = this.left;
      document.addEventListener('mousemove', this.startMove);
      document.addEventListener('mouseup', this.stopMove);
    },
    startMove(e) {
      const x = e.clientX - this.startX + this.start;
      this.left = Math.max(0, Math.min(x, 230));
      this.p=this.left/230*260
    },
    stopMove() {
      document.removeEventListener('mousemove', this.startMove);
      document.removeEventListener('mouseup', this.stopMove);
    }
  },
  beforeDestroy() {
    document.removeEventListener('mousemove', this.startMove);
    document.removeEventListener('mouseup', this.stopMove);
  }
}
</script>
<style scoped>
.btn{
  border-radius: 5px;
  box-shadow: 0 1px 2px 3px rgba(0,0,0,0.1);
}
.boxbtn{
  border-radius: 5px;
  overflow:hidden;
}
.bx{
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值