项目需要实现一个功能:点击按钮 需要动态创建一个input框,并且这个input框可拖动,还可以自己调整输入框的宽度,于是把一些原生的方法改成自定义指令来实现,可复用 很方便。
<div class="pdfList">
<img :src="previewImage">
<div v-for="(item,index) in elementList" :key="index" v-drag class="dragelement">
<input type="text" v-model="elementvalue" class="control">
<label v-inputdrag class="inputdragelement"> </label>
</div>
</div>
//注册局部组件指令
directives: {
drag: function (el) {
let dragBox = el; //获取当前元素
dragBox.onmousedown = e => {
//算出鼠标相对元素的位置
let disX = e.clientX - dragBox.offsetLeft;
let disY = e.clientY - dragBox.offsetTop;
document.onmousemove = e => {
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
//移动当前元素
dragBox.style.left = left + "px";
dragBox.style.top = top + "px";
};
document.onmouseup = e => {
//鼠标弹起来的时候不再移动
document.onmousemove = null;
//预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
document.onmouseup = null;
};
};
},
inputdrag: function (el) {
let inputdragBox = el; //获取当前元素
var isResizing = false,
lastDownX = 0;
var docu = null;
inputdragBox.onmousedown = e => {
e.stopPropagation();
docu = inputdragBox;
isResizing = true;
lastDownX = e.clientX;
console.log(e.clientX, e);
document.onmousemove = e => {
if (!isResizing) return;
var container = $(docu).prev(".control");
var offsetRight = (e.clientX - container.offset().left - container.width());
container.css("width", (container.width() + offsetRight-10) + "px");
};
document.onmouseup = e => {
isResizing = false;
//鼠标弹起来的时候不再移动
document.onmousemove = null;
//预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
document.onmouseup = null;
};
};
},
},
<style scoped lang="scss">
.pdfList{
position:relative;
}
.dragelement {
position: absolute;
z-index:1;
left:0px;
top:0px;
.control{
float:left
}
.inputdragelement{
float:left;
cursor:e-resize;
max-width:2px;
width:2px;
background:none;
}
}
</style>
网友评论