[JS+CSS+HTML]实现图片拖拽放大缩小功能
以下是实现图片拖拽和放大缩小功能的简单示例代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Zoom Image</title>
<style>
#imageContainer {
width: 600px;
height: 400px;
position: relative;
overflow: hidden;
cursor: move;
user-select: none;
}
img {
position: absolute;
width: 100%;
height: auto;
transform-origin: center center;
}
</style>
</head>
<body>
<div id="imageContainer">
<img id="draggableImage" src="path_to_your_image.jpg" alt="Drag Me">
</div>
<script>
let isDragging = false;
let startX, startY, distX, distY;
const imageContainer = document.getElementById('imageContainer');
const img = document.getElementById('draggableImage');
img.addEventListener('mousedown', function(e) {
isDragging = true;
startX = e.clientX - parseInt(img.style.left, 10);
startY = e.clientY - parseInt(img.style.top, 10);
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (isDragging) {
distX = e.clientX - startX;
distY = e.clientY - startY;
if (distX > 0 && distX < imageContainer.offsetWidth - img.offsetWidth) {
img.style.left = distX + 'px';
}
if (distY > 0 && distY < imageContainer.offsetHeight - img.offsetHeight) {
img.style.top = distY + 'px';
}
}
});
document.addEventListener('mouseup', function() {
isDragging = false;
});
// Zoom functionality
let scale = 1;
function zoomIn() {
scale *= 1.1;
img.style.transform = `scale(${scale})`;
}
function zoomOut() {
scale /= 1.1;
img.style.transform = `scale(${scale})`;
}
// Add zoom buttons
const zoomInBtn = document.createElement('button');
zoomInBtn.innerText = 'Zoom In';
zoomInBtn.onclick = zoomIn;
document.body.appendChild(zoomInBtn);
const zoomOutBtn = document.createElement('button');
zoomOutBtn.innerText = 'Zoom Out';
zoomOutBtn.onclick = zoomOut;
document.body.appendChild(zoomOutBtn);
</script>
</body>
</html>
请将 path_to_your_image.jpg
替换为您要使用的图片路径。
这段代码实现了以下功能:
- 图片可以通过鼠标拖动在容器内自由移动。
- 提供了
zoomIn
和zoomOut
函数来放大和缩小图片。 - 放大和缩小操作是通过 CSS 的
transform: scale()
实现的。
注意:这个示例没有考虑边界条件,如图片位置超出容器边界的情况。实际应用中可能需要添加相应的检查来避免这种情况发生。
评论已关闭