第一步
在utils下面新建一个directives.js文件,然后引入如下代码
const dragscroll = (el) => {
el.onmousedown = ev => {
const disX = ev.clientX;
const disY = ev.clientY; // 需要上下移动可以加
const originalScrollLeft = el.scrollLeft;
const originalScrollTop = el.scrollTop; // 需要上下移动可以加
const originalScrollBehavior = el.style['scroll-behavior'];
const originalPointerEvents = el.style['pointer-events'];
el.style['scroll-behavior'] = 'auto';
// 鼠标移动事件是监听的整个document,这样可以使鼠标能够在元素外部移动的时候也能实现拖动
document.onmousemove = dv => {
dv.preventDefault();
const distanceX = dv.clientX - disX;
const distanceY = dv.clientY - disY; // 需要上下移动可以加
el.scrollTo(originalScrollLeft - distanceX, originalScrollTop - distanceY); // 需要上下移动和左右移动
// el.scrollTo(originalScrollLeft - distanceX, 0); // 不需要上下拖拽,y轴值为0
};
document.onmouseup = () => {
document.onmousemove = null;
document.onmouseup = null;
el.style['scroll-behavior'] = originalScrollBehavior;
el.style['pointer-events'] = originalPointerEvents;
};
};
};
export default dragscroll;
第二步
在main.js中引入
import dragscroll from '@/utils/directives.js'
app.directive('dragscroll',dragscroll)
第三步文章来源:https://www.toymoban.com/news/detail-677479.html
页面直接使用即可文章来源地址https://www.toymoban.com/news/detail-677479.html
<div id="imgBox" v-dragscroll>
<img src="@/assets/images/image.svg" alt="" />
</div>
到了这里,关于vue3鼠标拖拽滑动效果的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!