Giter Club home page Giter Club logo

drag's Introduction

拖拽

拖拽元素分为两部分:拖拽源 origin和拖拽目标 target

拖拽相关事件涉及到:

  • 拖拽源:dragstartdragdragend
  • 拖拽目标:dragenterdragoverdragleavedrop

实现拖拽

  1. img 图片元素默认是能够拖拽的,其他元素需要设置 DOM 标签上的 draggable 属性为 true

  2. 另外为了保证 drop 事件的触发,需要在 dragover 事件中调用 event.preventDefault() 方法,已阻止默认事件。

数据通信

事件对象 event 中的 dataTransfer 属性用于在拖拽源和拖拽目标之间传递数据。

dataTransfer 属性中的 setData 方法用于设置数据,getData 方法用于获取数据。

另外,要注意的是,setData 方法只能设置字符串类型的数据,如果需要传递对象,需要使用 JSON.stringify 方法将对象转换为字符串。

譬如:

// 拖拽源
event.dataTransfer.setData('text/plain', JSON.stringify({ name: '张三' }))

// 拖拽目标
const data = JSON.parse(event.dataTransfer.getData('text/plain'))

drag's People

Contributors

oneyoung19 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.