用vue写图片放大镜效果的代码。
时间: 2024-05-23 20:14:46 浏览: 125
<template>
<div class="magnifier-container">
<div class="img-container">
<img :src="src" alt="图片">
<div class="magnifier"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
src: 'https://picsum.photos/400/300'
}
},
mounted() {
const imgContainer = document.querySelector('.img-container')
const magnifier = document.querySelector('.magnifier')
const img = imgContainer.querySelector('img')
const imgWidth = img.width
const imgHeight = img.height
const magnifierWidth = imgContainer.offsetWidth / 4
const magnifierHeight = imgContainer.offsetHeight / 4
// 设置放大镜的大小
magnifier.style.width = magnifierWidth + 'px'
magnifier.style.height = magnifierHeight + 'px'
// 监听鼠标移动事件,更新放大镜的位置和图片的位置
imgContainer.addEventListener('mousemove', e => {
const x = e.pageX - imgContainer.offsetLeft - magnifierWidth / 2
const y = e.pageY - imgContainer.offsetTop - magnifierHeight / 2
const maxX = imgContainer.offsetWidth - magnifierWidth
const maxY = imgContainer.offsetHeight - magnifierHeight
// 边界处理
if (x < 0) {
magnifier.style.left = 0
img.style.left = 0
} else if (x > maxX) {
magnifier.style.left = maxX + 'px'
img.style.left = -((imgWidth - imgContainer.offsetWidth) * magnifierWidth / imgWidth) + 'px'
} else {
magnifier.style.left = x + 'px'
img.style.left = -x * imgWidth / magnifierWidth + 'px'
}
if (y < 0) {
magnifier.style.top = 0
img.style.top = 0
} else if (y > maxY) {
magnifier.style.top = maxY + 'px'
img.style.top = -((imgHeight - imgContainer.offsetHeight) * magnifierHeight / imgHeight) + 'px'
} else {
magnifier.style.top = y + 'px'
img.style.top = -y * imgHeight / magnifierHeight + 'px'
}
})
}
}
</script>
<style>
.magnifier-container {
position: relative;
width: 400px;
height: 300px;
overflow: hidden;
}
.img-container {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.img-container img {
position: absolute;
top: 0;
left: 0;
transition: all 0.2s;
}
.magnifier {
position: absolute;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.3);
border-radius: 50%;
border: 1px solid #fff;
cursor: pointer;
transition: all 0.2s;
}
</style>
阅读全文