1.想要的效果
鼠标放到上面出现箭头显示可拖拽得图标
2.代码实现
2.1封装成自定义指令
// drawerDragDirective.js
// 定义指令
const drawerDragDirective = {
// 指令绑定时的处理函数
bind(el, ) {
const minWidth = 300;
const dragDom = el.querySelector('.el-drawer');
// 创建用于调整大小的元素
const resizeElL = document.createElement('div');
const img = new Image(24, 38);
dragDom.appendChild(resizeElL);
resizeElL.style.cursor = 'w-resize';
resizeElL.style.position = 'absolute';
resizeElL.style.height = '100%';
resizeElL.style.width = '10px';
resizeElL.style.left = '4px';
resizeElL.style.top = '0px';
img.style.position = 'absolute';
img.style.left = '-12px';
img.style.top = '50%';
// 鼠标按下事件处理函数
resizeElL.onmousedown = (e) => {
const elW = dragDom.clientWidth;
const EloffsetLeft = dragDom.offsetLeft;
const clientX = e.clientX;
document.onmousemove = function (e) {
e.preventDefault();
// 左侧鼠标拖拽位置
if (clientX > EloffsetLeft && clientX < EloffsetLeft + 10) {
// 往左拖拽
if (clientX > e.clientX) {
dragDom.style.width = elW + (clientX - e.clientX) + 'px';
}
// 往右拖拽
if (clientX < e.clientX) {
if (dragDom.clientWidth >= minWidth) {
dragDom.style.width = elW - (e.clientX - clientX) + 'px';
}
}
}
}
// 拉伸结束
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
}
};
// 导出指令
export default drawerDragDirective;
2.2 注册指令
import clickoutside from './clickoutside';
import dragX from "./dragX";
import elDragx from "./elDragX";
import resize from "./resize";
const Loading = {
install: function(Vue){
Vue.directive('clickoutside', clickoutside);
Vue.directive('dragx', dragX);
Vue.directive('resize', resize);
Vue.directive('el-dragx', elDragx);
}
};
export default Loading;
图片如下:
2.3在el-drawer中使用
至此,最终就实现了el-drwer可以通过鼠标进行拖拽来改变宽度。