1、起因
原因也比较简单,就是自己学习图片放大镜。现在需要有一个移动的蒙版图层。但是想到以后每次都需要重新写,就打算自己封装一个。但是又不想因为封装成组件导致页面结构变化很大。
过多的封装成组件有一个缺点:容易引起页面结构混乱。
所以就打算封装成指令模式。
2、直接上代码
这块的原理就不多说了,挺简单的。直接看我代码就行了。
区别在于我增加了一项,控制边界的问题。具体也很简单。大家仔细看代码就行了。
"use strict";
import vue from "vue";
// 传入参数true则控制边界不传和false则不控制边界,默认控制边界
//主函数
const directive = () => {
let expression = false;
vue.directive("DhtMove", {
inserted: function(el, binding) {
expression = binding.expression || expression;
let dragBox = el; //获取当前元素
dragBox.onmousedown = e => {
// 父元素宽高
let endWidth = e.target.parentNode.offsetWidth - e.target.offsetWidth;
let endHeight =
e.target.parentNode.offsetHeight - e.target.offsetHeight;
// 阻止默认事件,避免元素选中
e.preventDefault();
//算出鼠标相对元素的位置
let disX = e.x - dragBox.offsetLeft;
let disY = e.y - dragBox.offsetTop;
document.onmousemove = e2 => {
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e2.clientX - disX;
let top = e2.clientY - disY;
// 当传入true代表控制边界
if (expression) {
left = left > endWidth ? endWidth : left < 0 ? 0 : left;
top = top > endHeight ? endHeight : top < 0 ? 0 : top;
}
//移动当前元素
dragBox.style.left = left + "px";
dragBox.style.top = top + "px";
};
document.onmouseup = () => {
//鼠标弹起来的时候不再移动
document.onmousemove = null;
document.onmouseup = null;
};
};
},
update(el, binding) {
expression = binding.expression === "true";
},
unbind() {}
});
};
export default directive;
3、致谢
感谢简书的大神,代码主要参考来自他,这位的代码相当精简
地址:https://www.jianshu.com/p/f1ddb9b37a27
原文博客地址:https://www.dht.red/blog/blog_content?article_id=9