Vue 放大镜功能实现:完整代码及鼠标滚轮缩放
<div id="app">
<div class="container">
<div class="image-container" @mousemove="onMouseMove" @wheel="onWheel">
<img class="image" :src="imgSrc" :style="{transform: 'scale(' + scale + ')'}">
<div class="magnifier" :style="{backgroundImage: 'url(' + imgSrc + ')', backgroundSize: zoom}"></div>
</div>
</div>
</div>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.image-container {
position: relative;
}
.image {
width: 400px;
height: 400px;
object-fit: cover;
transition: transform 0.1s ease-out;
}
.magnifier {
position: absolute;
width: 200px;
height: 200px;
border: 2px solid #fff;
border-radius: 50%;
opacity: 0;
pointer-events: none;
}
.image-container:hover .magnifier {
opacity: 0.5;
}
.image-container:hover .image {
transform: scale(1.2);
transform-origin: 0 0;
}
</style>
<script>
new Vue({
el: '#app',
data: {
imgSrc: 'https://picsum.photos/id/237/800/800',
scale: 1,
zoom: '400px 400px'
},
methods: {
onMouseMove(event) {
const rect = event.target.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
this.zoom = '800px 800px'
this.$refs.magnifier.style.backgroundPosition = `-${x * 2}px -${y * 2}px`
},
onWheel(event) {
if (event.deltaY > 0) {
this.scale -= 0.1
} else if (event.deltaY < 0) {
this.scale += 0.1
}
}
}
})
</script>
<h2>实现思路</h2>
<ol>
<li>在HTML中,用<code><img></code>标签显示图片,并在<code><div></code>标签中创建一个放大镜容器。图片和放大镜容器都在一个外层容器中。</li>
<li>在CSS中,设置图片容器的<code>position</code>属性为<code>relative</code>,用<code>transition</code>属性实现图片放大效果,用<code>opacity</code>属性实现放大镜容器的透明度变化。</li>
<li>在Vue中,定义一个<code>imgSrc</code>变量,绑定到<code><img></code>标签的<code>src</code>属性上。定义一个<code>scale</code>变量,绑定到图片的<code>transform</code>属性上,用于实现放大缩小。定义一个<code>zoom</code>变量,绑定到放大镜容器的<code>backgroundSize</code>属性上,用于实现放大镜的缩放。</li>
<li>在Vue中,定义<code>onMouseMove</code>方法,用于实现鼠标移动时放大镜的位置和图片的放大效果。使用<code>getBoundingClientRect()</code>方法获取图片容器的位置信息,计算鼠标相对于图片容器的位置。根据鼠标位置设置放大镜容器的<code>backgroundPosition</code>属性,使其实时跟随鼠标移动。</li>
<li>在Vue中,定义<code>onWheel</code>方法,用于实现鼠标滚轮放大缩小图片。根据鼠标滚动方向调整<code>scale</code>变量的值,再绑定到图片的<code>transform</code>属性上,实现实时放大缩小效果。</li>
</ol>
原文地址: https://www.cveoy.top/t/topic/mW7V 著作权归作者所有。请勿转载和采集!