vue图片鼠标滚动放大镜功能代码实现
以下是一个简单的vue图片鼠标滚动放大镜功能的代码实现:
<template>
<div class="container">
<div class="image-container" ref="imageContainer">
<img
src="https://picsum.photos/500/300"
alt="image"
class="image"
ref="image"
@mousemove="handleMouseMove"
@mouseleave="handleMouseLeave"
/>
<div class="zoom" v-if="showZoom" ref="zoom"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showZoom: false,
zoomSize: 200,
zoomImageSize: 1000,
}
},
methods: {
handleMouseMove(event) {
const container = this.$refs.imageContainer
const image = this.$refs.image
const zoom = this.$refs.zoom
// 计算鼠标在图片上的位置
const x = event.pageX - container.offsetLeft
const y = event.pageY - container.offsetTop
// 计算放大镜位置
const zoomX = x - this.zoomSize / 2
const zoomY = y - this.zoomSize / 2
// 计算放大比例
const zoomRatio = this.zoomImageSize / image.width
// 设置放大镜样式
zoom.style.backgroundImage = `url(${image.src})`
zoom.style.backgroundPosition = `-${zoomX * zoomRatio}px -${zoomY * zoomRatio}px`
zoom.style.width = `${this.zoomSize}px`
zoom.style.height = `${this.zoomSize}px`
zoom.style.top = `${zoomY}px`
zoom.style.left = `${zoomX}px`
// 显示放大镜
this.showZoom = true
},
handleMouseLeave() {
// 隐藏放大镜
this.showZoom = false
},
},
}
</script>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.image-container {
position: relative;
}
.image {
display: block;
max-width: 100%;
}
.zoom {
position: absolute;
display: none;
border: 1px solid #ccc;
box-shadow: 0px 0px 5px #ccc;
overflow: hidden;
}
</style>
该代码实现了以下功能:
- 当鼠标在图片上移动时,显示一个放大镜,放大鼠标所在位置的图片部分;
- 放大镜的大小和放大比例可以通过data属性进行配置;
- 当鼠标离开图片时,隐藏放大镜。
该实现中的关键点在于计算放大镜的位置和样式。具体来说,需要计算鼠标在图片上的位置、放大镜的位置、放大比例等参数,然后设置放大镜的背景图片、大小、位置等样式。
原文地址: https://www.cveoy.top/t/topic/bpct 著作权归作者所有。请勿转载和采集!