如何用原生JS实现拖拽功能

预备知识

鼠标事件mousedown,mousemove,mouseup;

实现思路

1.当鼠标移入元素并且点击时,触发mousedown事件,让元素变为可移动状态;
2.当鼠标在移动时,触发mousemove先判断元素是否处于可移动状态,根据其状态决定该元素要不要移动;
3.当鼠标松开时,触发mouseup事件,使元素变为不可移动状态;

代码实现

先来一个小球:

  <div id="ball"></div>

样式:

#ball {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: black;
      cursor: pointer;
      position: absolute;
    }

mousedown事件

ball.addEventListener('mousedown', () => {
      isMove = true
    })

mousemove事件

document.addEventListener('mousemove', (e) => {
      if (!isMove) return
      let x = e.pageX - ball.offsetWidth / 2
      let y = e.pageY - ball.offsetHeight / 2
      ball.style.left = `${x}px`
      ball.style.top = `${y}px`
    })

mouseup事件

ball.addEventListener('mouseup', ()=> {
      isMove = false
    })

效果

效果图

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值