子绝父相,找不到借鉴文章了,自己记录一下,方便下次使用。
<!-- <img
src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp9.itc.cn%2Fq_70%2Fimages01%2F20211004%2F32293b4f3
2864bfda68b0c2c46a94d21.jpeg&refer=http%3A%2F%2Fp9.itc.cn&app=2002&size=f9999,10000&q=a80&n=0
&g=0n&fmt=auto?sec=1666251629&t=692439f3bfdc44961878348d8acb6915"
id="iframe-file"
style="width: 100%; height: 100%; position: absolute"
/> -->
mounted() {
this.$nextTick(() => {
const oBox = document.getElementById("iframe-file");
oBox.onmousedown = function (event) {
// 事件对象
const eventDown = event || window.event;
// 计算鼠标与盒子左侧和上方的距离
// 左侧距离 = 鼠标水平坐标-盒子左侧偏移距离(offsetLeft)
// 上方距离 = 鼠标垂直坐标-盒子上方偏移距离(offsetTop)
const lf = eventDown.clientX - oBox.offsetLeft;
const tp = eventDown.clientY - oBox.offsetTop;
// 2、鼠标移动,盒子随着鼠标移动而移动
document.onmousemove = function (event) {
event = event || window.event;
// 获取鼠标水平&垂直方向的坐标
const mouseLeft = event.clientX;
const mouseTop = event.clientY;
// console.log(mouseLeft - lf, '123456789', oBox.offsetLeft, fatherWidth)
// 设置盒子的left&top值,注意:要为元素加上定位
oBox.style.left = `${mouseLeft - lf}px`;
oBox.style.top = `${mouseTop - tp}px`;
// 3、松开鼠标,盒子停止
document.onmouseup = function () {
// 取消鼠标移动事件
document.onmousemove = null;
document.onmouseup = null;
};
/*
当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容,此时会导致拖拽功能异常,这是浏览器提供的默认行为,
如果不希望发生这个行为,则可以通过return false 来取消默认行为 但是这个对IE8一下不起作用
*/
return false;
};
};
});
},