Giter Site home page Giter Site logo

drag's Introduction

效果预览

交互场景:

  • 鼠标点击被拖拽的元素
  • 鼠标按住不放,移动被拖拽的元素
  • 鼠标松开,被拖拽的元素停留在该松开位置

实现思路:

  • 鼠标点击被拖拽的元素。绑定 mousedown事件
    • 设置当前拖拽状态为 true
    • 记录当前鼠标坐标
    • 记录当前被拖拽元素坐标
  • 鼠标按住不放,移动被拖拽的元素。document绑定 mousemove事件
    • 记录当前鼠标坐标
    • 若当前拖拽状态为true,元素的位移(坐标)= 当前鼠标坐标 - 初始鼠标坐标 + 被拖拽元素坐标(开始拖拽时初始坐标)
  • 鼠标松开,被拖拽的元素停留在该松开位置。document绑定 mouseup事件
    • 设置当前拖拽状态为 false

注意事项:

  • 被拖拽元素的postion属性须设置为relative/absolute
  • 鼠标坐标获取方式 event.clientX/event.clientY

drag-simple

以上实现上拖拽没问题,但拖拽范围过大。

如何实现在指定的区域(父元素区域)内拖动?

  • 获取拖拽元素和它的父元素宽高,父与子宽高两两相减,其结果为最大位移
  • 若当前拖拽状态为true,真实元素的位移(坐标)= 当前鼠标坐标 - 初始鼠标坐标 + 被拖拽元素坐标(开始拖拽时初始坐标)
  • 最终位移 = Math.min(最大位移坐标, Math.max( 0, 真实元素的位移(坐标))) + 'px'

drag-scope

总结以上功能,封装开箱即用。drag-scope-result

以上拖动均采用top/left,有没有动画性能更好的实现。

使用translate替代top/left

drag-scope-translate 总结以上功能,封装开箱即用。drag-scope-translate-result

若需要实现多个元素拖动

思路:每次鼠标按下时,利用this更新当前操作元素

总结以上功能,封装开箱即用。

drag's People

Contributors

fredafei avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.