• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Vue实现元素拖拽不过页面宽高

武飞扬头像
前端若水
帮助1

拖拽元素必须为固定定位

data(){
return{
 isLiveDrop:true
}
}
     /**
     * @function 元素拖拽
     * @param {*} dom id选择器
     */
    setDomDrop(dom) {
      const DROP = document.getElementById(dom)
      // 鼠标按下的初始坐标
      let StartX = null
      let StartY = null
      // 鼠标移动时候的坐标
      let MoveX = null
      let MoveY = null
      // 鼠标的最终位置
      let EndX = null
      let EndY = null
      // 获取盒子的初始值
      let DOMLeft = null
      let DOMTop = null
      // 元素的宽高
      let DOMHeight = null
      let DOMWidth = null
      //当前元素移动的最大距离
      let MaxX = null
      let MaxY = null
      // 当前元素移动最小距离
      let MinX = 0
      let MinY = 77
      // 元素的最终位置
      let DOMEndLeft = null
      let DOMEndTop = null
      const _this=this;
      // 鼠标按下
      DROP.onmousedown = function(e) {
        //鼠标按下事件
        e = e || window.event //事件对象
        StartX = e.clientX //鼠标按下X的坐标
        StartY = e.clientY //鼠标按下Y的坐标
        DOMLeft = this.offsetLeft //获取盒子的初始left值
        DOMTop = this.offsetTop //获取盒子的初始top值
        // 获取元素的宽
        DOMHeight = this.offsetHeight
        DOMWidth = this.offsetWidth
        // 获取元素的高
        document.onmousemove = function(e) {
          // 赋值为拖拽
          _this.isLiveDrop=false;
          //鼠标移动事件
          e = e || window.event
          MoveX = e.clientX //鼠标移动X的坐标
          MoveY = e.clientY //鼠标移动Y的坐标
          //移动的坐标减去按下的坐标 = 移动的距离
          EndX = MoveX - StartX
          EndY = MoveY - StartY
          // 当前页面可视区域内宽高-元素宽高=当前元素移动的最大距离
          MaxX = document.documentElement.clientWidth - DOMHeight //页面高度
          MaxY = document.documentElement.clientHeight - DOMWidth //页面宽度
          // 元素最终位置
          DOMEndLeft = DOMLeft   EndX
          DOMEndTop = DOMTop   EndY
          // 判断元素位置是否到达最小位置
          if (DOMEndLeft <= MinX) {
            DOMEndLeft = MinX
          }
          if (DOMEndTop <= MinY) {
            DOMEndTop = MinY
          }
          // 判断元素是否达到最大位置
          if (DOMEndLeft >= MaxX) {
            DOMEndLeft = MaxX
          }
          if (DOMEndTop >= MaxY) {
            DOMEndTop = MaxY
          }
          //赋值给left和top
          DROP.style.top =DOMEndTop  'px'
          DROP.style.left =DOMEndLeft  'px'
        }     
          //鼠标抬起事件
        document.onmouseup = function() {
   
          //清除移动和抬起事件
          this.onmousemove = this.onmouseup = null
          // 区分拖拽还是点击事件
          if(_this.isLiveDrop){
            _this.showLiveList()
          }
          _this.isLiveDrop=true;
        }
        return false //阻止默认事件
      }
    }

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhghcich
系列文章
更多 icon
同类精品
更多 icon
继续加载