帮我写一个鼠标滚轮控制放大缩小 鼠标长按拖动div
时间: 2023-05-31 10:07:11 浏览: 153
很高兴为您提供帮助。以下是一个简单的示例代码,可以实现鼠标滚轮控制放大缩小和鼠标长按拖动div的功能:
HTML代码:
```
<div id="container">
<img src="image.jpg" alt="Image">
</div>
```
CSS代码:
```
#container {
width: 500px;
height: 500px;
overflow: hidden;
position: relative;
}
#container img {
width: 100%;
}
#container .drag {
cursor: move;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
}
```
JavaScript代码:
```
var container = document.getElementById('container');
var image = container.getElementsByTagName('img')[0];
var drag = document.createElement('div');
drag.className = 'drag';
container.appendChild(drag);
var scale = 1;
var dragX = 0;
var dragY = 0;
var isDragging = false;
function handleWheel(event) {
var delta = event.deltaY / 100;
if (scale + delta >= 1) {
scale += delta;
image.style.transform = 'scale(' + scale + ')';
}
event.preventDefault();
}
function handleMouseDown(event) {
dragX = event.clientX;
dragY = event.clientY;
isDragging = true;
}
function handleMouseMove(event) {
if (isDragging) {
var deltaX = event.clientX - dragX;
var deltaY = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
container.scrollTo(container.scrollLeft - deltaX, container.scrollTop - deltaY);
}
}
function handleMouseUp() {
isDragging = false;
}
container.addEventListener('wheel', handleWheel);
drag.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
```
以上代码实现了在一个固定大小的div容器中放置一张图片,并且允许用户使用鼠标滚轮来放大或缩小图片,以及使用鼠标长按来拖动图片。希望可以对您有所帮助。
阅读全文