js中在页面中实现一张图片的拖拽
时间: 2024-02-20 16:58:45 浏览: 157
在JavaScript中实现图片的拖拽可以通过以下步骤:
- 首先需要在HTML中添加一张图片,并设置其id和class属性,如下所示:
<img src="path/to/image.jpg" id="myImage" class="draggable">
- 在JavaScript中获取该图片的元素对象,并添加鼠标按下和抬起的事件监听器,如下所示:
var myImage = document.getElementById("myImage");
myImage.addEventListener("mousedown", startDrag);
myImage.addEventListener("mouseup", stopDrag);
- 在鼠标按下事件的回调函数中,记录鼠标相对于图片左上角的偏移量,并添加鼠标移动的事件监听器,如下所示:
var offsetX, offsetY;
function startDrag(e) {
offsetX = e.clientX - myImage.offsetLeft;
offsetY = e.clientY - myImage.offsetTop;
document.addEventListener("mousemove", dragImage);
}
- 在鼠标移动事件的回调函数中,计算图片的位置,并更新其样式,如下所示:
function dragImage(e) {
var x = e.clientX - offsetX;
var y = e.clientY - offsetY;
myImage.style.left = x + "px";
myImage.style.top = y + "px";
}
- 最后,在鼠标抬起事件的回调函数中,移除鼠标移动事件的监听器,如下所示:
function stopDrag(e) {
document.removeEventListener("mousemove", dragImage);
}
综上所述,以上代码就可以实现在页面中拖拽一张图片的效果。需要注意的是,CSS样式需要设置图片的定位方式为绝对定位(position: absolute),并且该图片需要设置能够被拖拽的样式(如上述代码中的class属性为draggable)。
阅读全文
相关推荐


















