首先我们先来实现最简单的图片的拖拽,在这之前你需要了解 offsetLsft/offsetTop, clientX/clientY, onmousedown/onmousemove/onmousup 这里不做深入的讲解,我们直接看代码吧,注释写的很详细了(目前兼容性暂时只考虑了谷歌浏览器,其他浏览器思路相同,自行拓展)
html部分
<body>
<div id="app">
<img id="img"
src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2F1812.img.pp.sohu.com.cn%2Fimages%2Fblog%2F2009%2F11%2F18%2F18%2F8%2F125b6560a6ag214.jpg&refer=http%3A%2F%2F1812.img.pp.sohu.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625993298&t=9de0d6fb925f43ebe1f700162ee8d8c5">
</div>
</body>
css部分
js部分
<script>
/*先实现拖拽功能*/
const el = document.getElementById('img');
document.getElementsByTagName('body')[0].ondragstart = function () {
window.event.returnValue = false;
return false;
};
el.onmousedown = function(e) {
//先计算出鼠标按下那一刻,鼠标在图片上的位置
const OE = e || event;
const disX = OE.clientX - el.offsetLeft;
const disY = OE.clientY - el.offsetTop;
document.onmousemove = function (e) {
//鼠标移动的时候,动态设置图片的left和top的值来达到图片跟着鼠标移动的效果
const left = e.clientX - disX;
const top = e.clientY - disY;
el.style.left = left + 'px';
el.style.top = top + 'px';
};
}
document.onmouseup = function (e) {
// 鼠标放开事件
document.onmousedown = null;
document.onmousemove = null;
};
</script>
没有什么很特殊的地方,这个就是那几个属性和事件的使用,这样就完成了一个图片的拖拽功能