在需要这个效果的时候首先在npm仓库找到了vue-dragscroll
库,但是应用在我们自己项目上的时候拖动起来却非常慢,元素跟不上鼠标的移动速度,无奈,就自己简单的实现了一个拖拽指令:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import Vue from 'vue'
Vue.directive('dragscroll', function (el) { el.onmousedown = function (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.onmousemove = function (ev) { ev.preventDefault() const distanceX = ev.clientX - disX const distanceY = ev.clientY - disY el.scrollTo(originalScrollLeft - distanceX, originalScrollTop - distanceY) el.style['pointer-events'] = 'none' } document.onmouseup = function () { document.onmousemove = null document.onmouseup = null el.style['scroll-behavior'] = originalScrollBehavior el.style['pointer-events'] = originalPointerEvents } } })
|
由于我们项目使用了是Nuxtjs
,如果完全由后端渲染,是无法在document
上进行事件监听的,所以在nuxt.config.js
中这样定义插件:
1 2 3
| plugins: [ { src: '@/plugins/dragscroll', ssr: false } ],
|
最后可以在任何元素上应用该指令:
1
| <div dragscroll><img /></div>
|
最终的结果类似这样