js拖拽元素

html部分

<template>
  <div ref="content">
    <div class="signImg" @mousedown="moveDown"></div>
  </div>
</template>

css部分

<style lang="scss" scoped>
body,html{
  height: 100%;
}
.content{
  position: relative;
  top: 0;
  left: 0;
  width:700px;
  height: 1000px;
  border:1px solid black;
}
.signImg{
  position: absolute;
  bottom: 120px;
  right: 120px;
  background-color: red;
  width: 100px;
  height:100px;
}
</style>

js部分

data () {
    return {
      bottom: 120,   // 拖拽元素的初始位置
      right: 120

    }
},
methods: {
 moveDown (e) {
      e.preventDefault()

      const ele = e.target
      const _this = this

      // 向左移动的最大距离
      const maxY = _this.$refs.content.offsetHeight - ele.offsetHeight - 20
      // 向上移动的最大距离
      const maxX = _this.$refs.content.offsetWidth - ele.offsetWidth - 20

      // 鼠标位于电脑屏幕的初始位置
      const initX = document.documentElement.clientWidth - e.clientX
      const initY = document.documentElement.clientHeight - e.clientY

      // 鼠标开始移动
      document.onmousemove = function (even) {

        // 当前的鼠标鼠标位于电脑屏幕的位置
        const curX = document.documentElement.clientWidth - even.clientX
        const curY = document.documentElement.clientHeight - even.clientY

        // 当前鼠标移动的距离
        const left = curX - initX
        const height = curY - initY

        if (_this.right + left > maxX) {
          // 左边界限制
          ele.style.right = maxX + 'px'
        } else if (_this.right + left < 10) {
          // 右边界限制
          ele.style.right = 10 + 'px'
        } else {
          ele.style.right = _this.right + left + 'px'
        }

        if (_this.bottom + height > maxY) {
          // 上边界限制
          ele.style.bottom = maxY + 'px'
        } else if (_this.bottom + height < 10) {
          // 下边界限制
          ele.style.bottom = 10 + 'px'
        } else {
          ele.style.bottom = _this.bottom + height + 'px'
        }
      }

      document.onmouseup = function (even) {
        // 获取鼠标抬起时拖拽元素的位置
        if (ele.style.right) {
          _this.right = Number.parseInt(ele.style.right)
        }
        if (ele.style.bottom) {
          _this.bottom = Number.parseInt(ele.style.bottom)
        }

        // 关闭事件
        document.onmousemove = null
        document.onmouseup = null
      }
    },
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值