利用vue开发一套完整的(以鼠标位置为中心放大缩小)以及拖拽功能
时间: 2023-12-06 21:44:44 浏览: 57
好的,以下是一个简单的示例代码:
```html
<template>
<div class="container" ref="container" @mousemove="handleMouseMove">
<div class="image-container" ref="imageContainer" :style="imageStyle" @mousedown="handleMouseDown" @mouseup="handleMouseUp">
<img :src="imageUrl" alt="image" class="image" />
</div>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: "https://picsum.photos/800/600", // 图片地址
isDragging: false, // 是否在拖拽
lastX: 0, // 上一次鼠标位置
lastY: 0,
scale: 1 // 缩放比例
};
},
computed: {
imageStyle() {
return {
transform: `scale(${this.scale})`
};
}
},
methods: {
handleMouseMove(event) {
if (this.isDragging) {
const deltaX = event.clientX - this.lastX;
const deltaY = event.clientY - this.lastY;
const container = this.$refs.container;
const imageContainer = this.$refs.imageContainer;
const containerRect = container.getBoundingClientRect();
const imageRect = imageContainer.getBoundingClientRect();
if (
imageRect.left + deltaX <= containerRect.left &&
imageRect.right + deltaX >= containerRect.right
) {
imageContainer.style.left = `${imageRect.left + deltaX}px`;
}
if (
imageRect.top + deltaY <= containerRect.top &&
imageRect.bottom + deltaY >= containerRect.bottom
) {
imageContainer.style.top = `${imageRect.top + deltaY}px`;
}
this.lastX = event.clientX;
this.lastY = event.clientY;
}
},
handleMouseDown(event) {
this.isDragging = true;
this.lastX = event.clientX;
this.lastY = event.clientY;
},
handleMouseUp() {
this.isDragging = false;
}
}
};
</script>
<style>
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
}
.image-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.image {
display: block;
max-width: 100%;
height: auto;
}
</style>
```
这里使用了 `mousemove` 监听鼠标移动事件, `mousedown` 监听鼠标按下事件, `mouseup` 监听松开事件,实现了拖拽功能。同时,通过计算鼠标移动的距离,实现了图片的拖拽,并且限制了图片在容器内部移动。
同时,通过 `scale` 属性实现了图片的缩放功能,代码中通过 `computed` 计算属性来实现样式的动态绑定。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)