需求:图片放大后,看不到图片的全貌,需要鼠标拖动进行查看。
代码实现:
// 图片拖动
move(e){
let odiv = e.target; //获取目标元素
//阻止默认事件的方法,如果不阻止默认事件onmouseup会无法触发
e.preventDefault();
//算出鼠标相对元素的位置
let disX = e.clientX - odiv.offsetLeft;
let disY = e.clientY - odiv.offsetTop;
document.onmousemove = (e)=>{
//鼠标按下并移动的事件
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
//因为img居中对齐,所以还要减去目标元素距离body的偏移量
// let left = e.clientX - disX - odiv.offsetLeft;
let left = e.clientX - disX ;
let top = e.clientY - disY;
//移动当前元素
this.posLeft = left + 'px';
this.posTop = top + 'px';
// odiv.style.left = left + 'px';
// odiv.style.top = top + 'px';
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
} ,
网友评论