JavaScript实现图片鼠标位置的放大缩小及拖拽功能示例
时间: 2023-10-14 13:30:34 浏览: 119
以下是一个简单的JavaScript实现图片鼠标位置的放大缩小及拖拽功能的示例:
HTML代码:
```html
<div id="image-container">
<img id="image" src="example.jpg" />
</div>
```
CSS代码:
```css
#image-container {
width: 500px;
height: 500px;
overflow: hidden;
position: relative;
}
#image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: move;
}
```
JavaScript代码:
```javascript
var container = document.getElementById("image-container");
var image = document.getElementById("image");
// 初始缩放比例为1
var scale = 1;
// 鼠标按下时的位置
var mouseX = 0;
var mouseY = 0;
// 鼠标是否按下
var isMouseDown = false;
// 鼠标按下时记录鼠标位置
container.addEventListener("mousedown", function(event) {
isMouseDown = true;
mouseX = event.clientX;
mouseY = event.clientY;
});
// 鼠标松开时重置鼠标状态
container.addEventListener("mouseup", function(event) {
isMouseDown = false;
});
// 鼠标移动时缩放或拖拽图片
container.addEventListener("mousemove", function(event) {
if (isMouseDown) {
// 鼠标按下时拖拽图片
var deltaX = event.clientX - mouseX;
var deltaY = event.clientY - mouseY;
image.style.left = parseInt(image.style.left) + deltaX + "px";
image.style.top = parseInt(image.style.top) + deltaY + "px";
mouseX = event.clientX;
mouseY = event.clientY;
} else {
// 鼠标未按下时缩放图片
var deltaScale = 0;
if (event.deltaY < 0) {
deltaScale = 0.1;
} else if (event.deltaY > 0) {
deltaScale = -0.1;
}
scale += deltaScale;
// 最小缩放比例为0.1
scale = Math.max(scale, 0.1);
image.style.transform = "scale(" + scale + ")";
}
});
```
这段代码实现了以下功能:
1. 鼠标按下并拖拽图片时,图片跟随鼠标移动。
2. 鼠标未按下时,通过滚轮上下滑动实现图片的放大缩小,最小缩放比例为0.1。
阅读全文