写一个使用vue的指令v-drag来实现鼠标拖拽,再结合css的transform属性实现横向滚动效果的代码
时间: 2024-05-29 11:08:52 浏览: 134
可以的,以下是示例代码:
Vue.directive('drag', {
bind: function (el, binding) {
var startX, startY, initialMouseX, initialMouseY;
el.addEventListener('mousedown', function (e) {
startX = el.scrollLeft;
startY = el.scrollTop;
initialMouseX = e.clientX;
initialMouseY = e.clientY;
el.addEventListener('mousemove', drag);
el.addEventListener('mouseup', stopDrag);
});
function drag(e) {
var deltaX = e.clientX - initialMouseX;
var deltaY = e.clientY - initialMouseY;
el.scrollLeft = startX - deltaX;
el.scrollTop = startY - deltaY;
}
function stopDrag() {
el.removeEventListener('mousemove', drag);
el.removeEventListener('mouseup', stopDrag);
}
}
});
使用方法:
<div v-drag style="width: 400px; height: 200px; overflow-x: scroll;">
<div style="width: 800px; height: 200px;"></div>
</div>
这样就可以在鼠标按下时拖动滚动条实现横向滚动效果了。
阅读全文