在做后端管理系统中,像弹窗或大的表单时,经常会有滚动条的出现,但有些时候如流程、图片等操作时,仅仅使用鼠标拖动滚动条操作不太方便,如果使用鼠标拖拽图片或容器来触发滚动条的移动就比较方便了
如果要实现鼠标辅助触发滚动条的移动,需要借助 mousedown,mouseup,mousemove 三个事件,通过鼠标的移动来动态修改滚动条的scrollLeft和scrollTop,来模拟实现滚动条的位置变更。
考虑到鼠标的拖动有独立和可复用性,可以创建一个类来封装鼠标事件,使用时只要把事件挂到指定的容器上,就可以实现功能的复用
创建move.js
// 鼠标移动滚动位置类
class Drag {
constructor(vm) {
this.dragWrap = vm;// 要挂载的容器
this._dom = {};
this._x = 0;
this._y = 0;
this._top = 0;
this._left = 0;
this.move = false;
this.down = false;
this.init.apply(this, arguments);
}
// 绑定事件
init() {
this.bindEvent();
}
// 给要素增加鼠标事件
// mousedown 按下初始化
// mousemove 移动
// mouseup,mouseleave 松开,移出结束移动
bindEvent() {
let t = this;
this.dragWrap.addEventListener('mousedown', (e) => {
e && e.preventDefault();
if (!t.move) {
t.move = false;
t.down = true;
t._x = e.clientX;
t._y = e.clientY;
t._top = t.dragWrap.scrollTop;
t._left = t.dragWrap.scrollLeft;
}
});
this.dragWrap.addEventListener('mouseup', (e) => {
e && e.preventDefault();
t.move = false;
t.down = false;
});
this.dragWrap.addEventListener('mouseleave', (e) => {
e && e.preventDefault();
t.move = false;
t.down = false;
});
this.dragWrap.addEventListener('mousemove', (e) => {
if (t.down) {
e && e.preventDefault();
t.move = true;
let x = t._x - e.clientX;
let y = t._y - e.clientY;
t.dragWrap.scrollLeft = t._left + x;
t.dragWrap.scrollTop = t._top + y;
}
});
}
}
export default Drag;
1.在页面中使用move.js类,实现鼠标移动触发滚动条位置的移动
2.给svg添加放大功能
<template>
<el-row class="app-container">
<el-col>
<el-form ref="form" v-model="value" label-width="80px" size="mini" style="position: absolute;top: 32px;z-index: 999;">
<el-form-item label="缩放" prop="value">
<el-input-number v-model="value" @change="changeSlider" :min="0" :max="3"></el-input-number>
</el-form-item>
</el-form>
<div id="navShow" style="text-align: center;overflow: hidden;height:90vh;border: 1px solid #000000;">
<div>
<svg id="svgShow" style="cursor:pointer;width:96%;height:96%;padding: 10px;"></svg>
</div>
</div>
</el-col>
</el-row>
</template>
<script>
import Drag from '@/utils/move.js';
export default {
name: 'ProcessingFlow',
data() {
return {
value: 2,
}
},
mounted() {
this.changeSlider()
this.initScroll()
},
methods: {
changeSlider() {
let svg = document.getElementById('svgShow')
if (this.value === 1) {
svg.style.transform = 'scale(1.6)'
} else if (this.value === 2) {
svg.style.transform = 'scale(1.9)'
} else if (this.value === 3) {
svg.style.transform = 'scale(2.2)'
} else {
svg.style.transform = 'scale(1)'
}
svg.style.transformOrigin = ' 0 0'
let nav = document.getElementById('navShow')
// 滚动元素的父容器:刷新滚轮
nav.scrollIntoView()
},
initScroll() {
let nav = document.getElementById('navShow')
new Drag(nav)
},
}
}
</script>
<style scoped>
</style>
实现效果