介绍
interactjs是开源js库,可以实现元素拖拽,放大缩小等交互,简单轻量。官方API文档是英文的,但是有示例演示,上手还算简单。
用法
npm install interactjs -S
import interact from 'interactjs'
data () {
return {
componentList: []
}
},
methods: {
setPos (target, x, y, w, h) {
target.style.left = x + 'px'
target.style.top = y + 'px'
target.style.width = w + 'px'
target.style.height = h + 'px'
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
target.setAttribute('data-w', w)
target.setAttribute('data-h', h)
},
init () {
let self = this
const zoomItem = interact('.newitem')
zoomItem.resizable({
edges: { left: true, right: true, bottom: true, top: true },
listeners: {
move (event) {
let target = event.target
let x = (parseFloat(target.getAttribute('data-x')) || 0)
let y = (parseFloat(target.getAttribute('data-y')) || 0)
let w = event.rect.width
let h = event.rect.height
x += event.deltaRect.left
y += event.deltaRect.top
self.setPos(target, x, y, w, h)
}
},
modifiers: [
interact.modifiers.restrictEdges({
outer: 'parent'
}),
interact.modifiers.restrictSize({
min: { width: 100, height: 50 }
})
],
inertia: true
})
zoomItem.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: {
move: dragMoveZoomListener
}
})
function dragMoveZoomListener (event) {
let target = event.target
let x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
let y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
let w = (parseFloat(target.getAttribute('data-w')) || event.rect.width)
let h = (parseFloat(target.getAttribute('data-h')) || event.rect.height)
self.setPos(target, x, y, w, h)
}
}
},
mounted () {
this.init()
}
<div class="newitem"
:id="item.id"
:data-x="item.x"
:data-y="item.y"
:data-w="item.w"
:data-h="item.h"
:style="{
left: item.x,
top: item.y,
width: item.w,
height: item.h,
zIndex: item.zIndex
}"
v-for="(item, idx) in componentList" :key="idx">
// 要渲染的代码
</div>
.newitem{
position: absolute;
display: inline-block;
touch-action: none;
transform: translate(0px, 0px);
transition: background-color 0.3s;
border: 0.8px dashed #ddd;
box-sizing: border-box;
border-radius: 4px;
}
效果图.png
相关链接
官网
github - interactjs
演示项目: https://github.com/xiaoxia107/drag-vue
网友评论