要使图片在父div中可拖动,可以通过以下步骤实现:
以下是一个示例代码:
HTML:
<div id="parentDiv" style="position: relative; width: 400px; height: 400px; border: 1px solid black;">
<img id="dragImg" src="your_image_url" style="position: absolute; top: 0; left: 0; width: 100px; height: 100px;">
</div>
JavaScript:
var dragImg = document.getElementById("dragImg");
var parentDiv = document.getElementById("parentDiv");
var isDragging = false;
var initialX, initialY;
dragImg.addEventListener("mousedown", function(event) {
isDragging = true;
initialX = event.clientX - dragImg.offsetLeft;
initialY = event.clientY - dragImg.offsetTop;
});
document.addEventListener("mousemove", function(event) {
if (isDragging) {
var newX = event.clientX - initialX;
var newY = event.clientY - initialY;
dragImg.style.left = newX + "px";
dragImg.style.top = newY + "px";
}
});
document.addEventListener("mouseup", function() {
isDragging = false;
});
这样,当鼠标按下并移动时,图片将跟随鼠标移动,实现了图片在父div中的拖动效果。
腾讯云相关产品推荐:无
领取专属 10元无门槛券
手把手带您无忧上云