个人学习笔记
<div class="previewP_main" >
<img :src="otheruserinfo.image" alt="" ref="img" @mousedown="move" />
</div>
methods: {
move(e){
let odiv = e.target; //获取目标元素
//阻止默认事件的方法,如果不阻止默认事件onmouseup会无法触发
e.preventDefault();
//算出鼠标相对元素的位置
let disX = e.clientX - odiv.offsetLeft;
let disY = e.clientY - odiv.offsetTop;
document.onmousemove = (e)=>{
console.log("移动")
//鼠标按下并移动的事件
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
//因为img居中对齐,所以还要减去目标元素距离body的偏移量
let left = e.clientX - disX - odiv.offsetLeft;
let top = e.clientY - disY;
//移动当前元素
odiv.style.left = left + 'px';
odiv.style.top = top + 'px';
};
document.onmouseup = (e) => {
console.log("停止")
document.onmousemove = null;
document.onmouseup = null;
};
}
}
.previewP_main{
padding-top: 53px;
//图片居中
text-align: center;
img{
width: 500px;
position: relative;
}
}
网友评论