在上一篇文章中我们讲到了Drag的drag和whileDrag属性,这只是Drag拖动属性冰山一角,这篇文章将介绍它的其他属性
1.dragConstraints
解释:对可拖动区域应用约束。设置为可选
top、left、right和bottom值的对象,以像素为单位测量
代码部分:
<!-- 限制横轴移动、样式 、拖动限制 --> <motion.div drag="x" style="width: 100px;height: 100px;background-color: lawngreen;" :dragConstraints="{ left: 0, right: 300 }" />实际效果:
对比红色方块可以看到绿色方块的左右拖动存在限制
当然此属性还有另外一种用法:
作为对另一个元素的 ref,以使用其边界框作为可拖动约束
什么意思呢?假如我们有两个盒子,一个大一个小,小盒子在大盒子里面,小盒子的可拖动范围不超过大盒子的边界
代码如下:
<script setup> import { useDomRef } from "motion-v" const constraintsRef = useDomRef() </script> <template> <motion.div ref="constraintsRef" style="width: 200px;height: 200px;border: 1px solid black;"> <motion.div style="width: 50px;height: 50px;background-color: red;" drag :dragConstraints="constraintsRef" /> </motion.div> </template>这里出现了一个陌生的方法:useDomRef,这个解释我在中文的文档中并没有找到对应的解释,在英文的文档中是这样说的
Or, it can accept an HTMLElement ref value. You can get the component's DOM
ref value usinguseDomReffrommotion-v, and pass it both to the draggable
component'sdragConstraintsprop and the ref of the component you want to
use as constraints.
这段话总结下来就是使用 useDomRef 从 motion-v 库中获取你想要作为约束边界的组件的DOM引用,就是获取 motion-v Dom的方法。
下面我们看具体的效果:
2.dragSnapToOrigin
解释:默认值为
false,如果为true,则可拖动元素在释放时将动画返回到其中心/原点。
代码如下:
<motion.div drag dragSnapToOrigin style="width: 100px;height: 100px;background-color: palevioletred;" />实际效果如下:
3.dragElastic
解释:默认值为0.5,约束外部允许的移动程度。0 = 不移动,1 = 完全移动。默认设置为 0.5。也可以设置为 false 以禁用移动。通过传递 top/right/bottom/left 的对象,可以为每个约束设置单独的值。任何缺失的值都将设置为 0。
代码如下:
<motion.div drag="x" :dragConstraints="{ left: 0, right: 300 }" :dragElastic="0.1" style="width: 100px;height: 100px;background-color: palevioletred;" /> <!-- 对比组 --> <motion.div drag="x" :dragConstraints="{ left: 0, right: 300 }" :dragElastic="0.6" style="width: 100px;height: 100px;background-color: green;" />实际效果如下,上方的方块dragElastic为0.1,下方dragElastic为0.6:
以上就是本文章的主要内容,如果感兴趣,可以前往Motion库官网查看具体文档。
Motion for Vue 入门 | Motion for Vue - Motion 动画库