Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

拖拽图片遇到的坑(图片可点击) #53

Open
Lee981265 opened this issue Nov 3, 2020 · 0 comments
Open

拖拽图片遇到的坑(图片可点击) #53

Lee981265 opened this issue Nov 3, 2020 · 0 comments

Comments

@Lee981265
Copy link
Member

Lee981265 commented Nov 3, 2020

封装成指令

背景

需要做一个客服悬窗 可拖拽 可点击展开客服聊天界面 我的结构是div 包 img

踩坑

  • 直接使用现成的npm包会发现 图片偶出现禁止拖拽 代码已经加上 dragable=true 然并卵
  • 会出现拖拽位置和鼠标不对(不能跟随鼠标切有延时)
  • 边界超出
  • 拖拽完成直接点击打开客服弹窗了

代码思路

  • 为了避免图片拖拽出现禁止拖拽 把图片换成div+background-image
  • 不能跟随鼠标切有延时实质上是鼠标拖拽起始接触拖拽体的位置没有减去
  • 临界值处理
    • [0,document.documentElement.clientHeight - el.offsetHeight]
    • [0,document.documentElement.clientWidth - el.offsetWidth]
  • 事件处理
  • 拖拽整个过程事件经过 [onmousedown,onmousemove,onmouseup,click] 只枚举我下面用到的
  • 区别拖拽与点击 通过,onmousemove=>onmouseup过程的时间间隔 我这里是200ms
  • 设置一个id自动点击
const Drag: any = {}

Drag.install = (Vue, options = {}) => {
  Vue.directive('drag', {
    inserted(el,binding) {
      const { id } = binding.value
      el.onmousedown = function(ev) {
        // 用元素距离视窗的X、Y坐标,减去el元素最近的相对定位父元素的left、top值
        var sX = ev.clientX - el.offsetLeft
        var sY = ev.clientY - el.offsetTop
        // 不断地更新元素的left、top值
        document.onmousemove = function(ev) {
          el.setAttribute('data-flag', false)
          let top = ev.clientY - sY
          if (top < 0) {
            top = 0
          } else if (
            top >
            document.documentElement.clientHeight - el.offsetHeight
          ) {
            top = document.documentElement.clientHeight - el.offsetHeight
          }
          el.style.top = top + 'px'
        }
        const firstTime = new Date().getTime()
        document.onmouseup = function(event) {
          document.onmousemove = null
          document.onmouseup = null
          const lastTime = new Date().getTime()
          if (lastTime - firstTime < 200) {
            // 点击
            el.setAttribute('data-flag', true)
            document.getElementById(id).click()
          }
        }
      }
    }
  })
}

export default Drag

使用

    <div class="darg-smart" v-drag="{id:'smart'}" @load="changeImg(this)">
      <div class="img-smart" v-show="!showSamrt"></div>
    </div>
    <div id="smart" @click="showSamrt = true"></div>
    <SmartCustomerService v-if="showSamrt" @weClose="onClose" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant