1、创建一个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;
2、在main.js中引入这个js
import dragscroll from '@utils/directives.js';
app.directive('dragscroll',dragscroll);
3、在页面中使用
<ul class="navBar" id="nav" v-dragscroll>
<li>拖动1</li>
<li>拖动2</li>
<li>拖动3</li>
<li>拖动4</li>
<li>拖动5</li>
<li>拖动6</li>
<li>拖动7</li>
<li>拖动8</li>
<li>拖动9</li>
<li>拖动10</li>
</ul>
4、效果
文章来源:https://www.toymoban.com/news/detail-500139.html
参考文章(https://www.jianshu.com/p/6681c8b0a10a)文章来源地址https://www.toymoban.com/news/detail-500139.html
到了这里,关于vue 自定义指令(鼠标拖拽滑动)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!