<template>
<div>
<div v-magnify ref="content" class="content">
<img src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" alt="">
</div>
</div>
</template>
<script>
export default {
directives: {
magnify: {
bind(el, bindings, vnode) {
let magnifier
function handleMouseMove(event) {
magnifier.style.left = `${event.offsetX}px`
magnifier.style.top = `${event.offsetY}px`
const backgroundPositionX = -event.offsetX + 'px'
const backgroundPositionY = -event.offsetY / 2 + 'px'
magnifier.style.transform = 'scale(1.4)'
magnifier.style.backgroundPosition = `${backgroundPositionX} ${backgroundPositionY}`
}
vnode.context.$nextTick(() => {
magnifier = document.createElement('div')
magnifier.className = 'magnifier'
el.appendChild(magnifier)
magnifier.style.display = 'none'
})
el.addEventListener('mousemove', handleMouseMove)
el.addEventListener('mouseenter', () => {
const imgTag = el.querySelector('img')
magnifier.style.backgroundImage = `url(${imgTag.src})`
magnifier.style.display = 'block'
})
el.addEventListener('mouseleave', () => {
magnifier.style.display = 'none'
})
}
}
}
}
</script>
<style>
.magnifier {
position: absolute;
width: 200px;
height: 200px;
border: 1px solid #ccc;
z-index: 999;
background-color: rgba(255, 255, 255, 0.5);
}
.content{
height:800px;
width: 800px;
}
img{
width: 100%;
height: 100%;
}
</style>