html-drag
v1.0.22
Published
A tool for dragging html dialog element easily
Downloads
4
Readme
html-drag
A tool for dragging html dialog element easily
Preview
Setup
Node
npm install --save html-drag
Browser
<script src="./dist/html-drag.min.js"></script>
Usage
You can then use it as a window global or as an CommonJs module
// plain javascript in browser
Dragger.dragHtml(opt)
// commonJs
const { dragHtml } = require('html-drag')
// es6 module 使用ES6模块,需要在项目中集成webpack等打包工具
/**
* If you want to use this library by esm, you must ensure that your project
* has used webpack, vite, rollup or other packaging tools.
*/
import { dragHtml } from 'html-drag'
// option
const opt = {
// html element's anchor to be dragged 拖拽的锚点
anchorTarget: Header,
// html element to be dragged 拖拽时移动的元素
draggedTarget: Panel,
// anchor cursor style 锚点的鼠标样式(可选配置,默认值为'default')
anchorCursorStyle?: 'move',
// mouse style in dragging 拖拽时的鼠标样式(可选配置,默认值为'default')
cursorStyle?: 'move',
// 坐标轴限制, 当为'x', 'y', 'xy'时,限制在该轴上拖动, 默认不限制
limitAxis: '',
/**
* open parent container boundary limit
* 是否开启父容器的边界限制(可选配置,默认值为true)
*/
isOpenBoundary?: true,
// whether touch is supported 是否支持触摸(可选配置,默认值为true)
isOpenTouch?: true,
// 是否在捕获阶段执行鼠标移动和弹起事件,开启后事件不会向下传递,默认为false
// 当鼠标移动受其他元素影响时,设置为true
isUseCapture?: false,
// callback function when dragging 拖动时的回调函数(可选配置)
onDrag?: (left, top, dx, dy) => {
// 不返回任何值,仅在拖动时执行
// 返回false时,被拖动元素的位置将不发生改变
// 该函数可以返回一个左、上距离的数组,对拖动过程中的拖动范围做进一步限制,单位为px
if(left < 20) {
left = 20
} else if(left > 80) {
left = 80
}
if(top < 20) {
top = 20
} else if(top > 80) {
top = 80
}
return [left, top]
},
// 拖动开始时的回调函数(可选配置)
onDragStart: () => {
console.log('drag start!')
},
// 拖动结束时的回调函数(可选配置)
onDragEnd: () => {
console.log('drag end!')
}
}
// Use dragHtml to make html element draggable
const destroyEvent = dragHtml(opt)
// Return value
// Return a function to destroy dragging after calling
destroyEvent()
Example
Html
<body>
<div id="Panel">
<div id="PanelHeader">header</div>
<div>content</div>
</div>
<script>
const Panel = document.getElementById('Panel')
const Header = document.getElementById('PanelHeader')
Dragger.dragHtml({
anchorTarget: Header,
draggedTarget: Panel,
cursorStyle: 'move',
})
</script>
</body>
Vue
// 在vue中使用
<template>
<div ref='Panel'>
<div ref='PanelHeader'>header</div>
<div>content</div>
</div>
</template>
<script>
import { dragHtml } from 'html-drag'
let dragEvent
mounted() {
dragEvent = dragHtml({
anchorTarget: this.$refs.PanelHeader,
draggedTarget: this.$refs.Panel,
cursorStyle: 'move'
})
},
beforeDestroy() {
if (dragEvent) {
dragEvent()
}
}
</script>