Draggable.js 开源项目教程
Draggable.js 开源项目教程draggableThe JavaScript Drag & Drop library your grandparents warned you about.项目地址:https://gitcode.com/gh_mirrors/dr/draggable 项目介绍Draggable.js 是一个模块化的拖放库,由 Shopify 开发并开源。它允许用户快...
·
Draggable.js 开源项目教程
项目介绍
Draggable.js 是一个模块化的拖放库,由 Shopify 开发并开源。它允许用户快速实现拖放功能,支持快速 DOM 重排序、无障碍标记以及一系列事件处理。Draggable.js 提供了多种功能模块,如 Swappable、Sortable 和 Droppable,以满足不同场景的需求。
项目快速启动
安装
首先,通过 npm 或 yarn 安装 Draggable.js:
npm install @shopify/draggable
或者使用 yarn:
yarn add @shopify/draggable
基本使用
以下是一个简单的示例,展示如何在项目中使用 Draggable.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Draggable Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/@shopify/draggable@1.0.0/lib/draggable.bundle.js"></script>
<script>
const containers = document.querySelectorAll('.container');
const draggable = new Draggable.Draggable(containers, {
draggable: '.item'
});
draggable.on('drag:start', () => console.log('Drag started'));
draggable.on('drag:move', () => console.log('Drag moving'));
draggable.on('drag:stop', () => console.log('Drag stopped'));
</script>
</body>
</html>
应用案例和最佳实践
案例一:任务列表
在任务管理应用中,使用 Draggable.js 可以轻松实现任务项的拖放排序:
<div class="task-list">
<div class="task">Task 1</div>
<div class="task">Task 2</div>
<div class="task">Task 3</div>
</div>
<script>
const taskList = document.querySelector('.task-list');
const sortable = new Draggable.Sortable(taskList, {
draggable: '.task'
});
</script>
案例二:图片墙
在图片展示应用中,使用 Draggable.js 可以实现图片的拖放和交换:
<div class="photo-wall">
<img src="photo1.jpg" class="photo">
<img src="photo2.jpg" class="photo">
<img src="photo3.jpg" class="photo">
</div>
<script>
const photoWall = document.querySelector('.photo-wall');
const swappable = new Draggable.Swappable(photoWall, {
draggable: '.photo'
});
</script>
典型生态项目
Vue Draggable
Vue Draggable 是一个基于 Draggable.js 的 Vue 组件,提供了拖放功能并与 Vue 的数据绑定完美结合。
安装
npm install vuedraggable
使用
<template>
<div>
<draggable v-model="myArray" group="people" @start="drag=true" @end="drag=false">
<div v-for="element in myArray" :key="element.id">
{{element.name}}
</div>
</draggable>
</div>
</template>
<script>
import draggable from 'vuedraggable';
export default {
components: {
draggable
},
data() {
return {
myArray: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
};
}
};
</script
更多推荐

所有评论(0)