帮我生成一段最简洁vue2的实现图片放大镜效果的代码
时间: 2023-05-27 09:04:15 浏览: 176
图片放大镜效果源代码
5星 · 资源好评率100%
以下是一个最简洁的Vue2实现图片放大镜效果的代码:
Template:
```html
<template>
<div class="image-zoom-container">
<div class="image-zoom" ref="imageZoom" :style="{backgroundImage: 'url(' + imageUrl + ')'}"></div>
<div class="image" :style="{backgroundImage: 'url(' + imageUrl + ')'}" @mousemove="handleMouseMove" @mouseleave="handleMouseLeave"></div>
</div>
</template>
```
Style:
```css
.image-zoom-container {
position: relative;
}
.image-zoom {
position: absolute;
top: 0;
left: 0;
z-index: 999;
width: 150px;
height: 150px;
border-radius: 50%;
border: 2px solid #fff;
background-position: center center;
background-repeat: no-repeat;
display: none;
}
.image {
width: 100%;
height: auto;
background-position: center center;
background-repeat: no-repeat;
}
.image:hover + .image-zoom {
display: block;
}
```
Script:
```javascript
<script>
export default {
name: "ImageZoom",
props: {
imageUrl: String
},
data() {
return {
zoomed: false,
xPosition: 0,
yPosition: 0
};
},
methods: {
handleMouseMove(event) {
const element = this.$refs.imageZoom;
const { left: x, top: y } = event.currentTarget.getBoundingClientRect();
const xPosition = event.clientX - x - element.offsetWidth / 2;
const yPosition = event.clientY - y - element.offsetHeight / 2;
const bgPosX = (-1 * xPosition) * 2;
const bgPosY = (-1 * yPosition) * 2;
element.style.transform = "translate3d(" + xPosition + "px," + yPosition + "px, 0) scale3d(2, 2, 1.0)";
element.style.backgroundPosition = "center center";
element.style.backgroundPositionX = bgPosX + "px";
element.style.backgroundPositionY = bgPosY + "px";
},
handleMouseLeave() {
const element = this.$refs.imageZoom;
element.style.transform = "translate3d(0, 0, 0) scale3d(1, 1, 1.0)";
},
},
};
</script>
```
使用:
```html
<ImageZoom imageUrl="https://picsum.photos/500/300" />
```
以上代码实现了一个简单的图片放大镜效果,当鼠标指针悬停在图片上方时,会出现一个150x150大小的圆形放大镜,随着鼠标的移动,放大镜中显示的图片会随之变化。当鼠标移开时,放大镜消失。
阅读全文