鼠标放图片放大镜是一种常见的网页交互效果,当用户将鼠标悬停在图片上时,会显示一个放大的视图。这种效果通常通过HTML、CSS和JavaScript来实现。
以下是一个简单的JavaScript鼠标放图片放大镜的实现示例:
<div class="magnifier">
<img src="path/to/image.jpg" alt="Image" id="image">
<div id="lens"></div>
<div id="result"></div>
</div>.magnifier {
position: relative;
display: inline-block;
}
#lens {
position: absolute;
border: 1px solid #d4d4d4;
width: 100px;
height: 100px;
background-color: rgba(255, 255, 255, 0.4);
cursor: none;
display: none;
}
#result {
position: absolute;
top: 0;
left: 100%;
width: 300px;
height: 300px;
border: 1px solid #d4d4d4;
background-repeat: no-repeat;
display: none;
}document.addEventListener('DOMContentLoaded', function() {
const image = document.getElementById('image');
const lens = document.getElementById('lens');
const result = document.getElementById('result');
const cx = result.offsetWidth / lens.offsetWidth;
const cy = result.offsetHeight / lens.offsetHeight;
image.addEventListener('mousemove', moveLens);
lens.addEventListener('mousemove', moveLens);
function moveLens(e) {
e.preventDefault();
const pos = getCursorPos(e);
let x = pos.x - (lens.offsetWidth / 2);
let y = pos.y - (lens.offsetHeight / 2);
if (x > image.width - lens.offsetWidth) {
x = image.width - lens.offsetWidth;
}
if (x < 0) {
x = 0;
}
if (y > image.height - lens.offsetHeight) {
y = image.height - lens.offsetHeight;
}
if (y < 0) {
y = 0;
}
lens.style.left = x + 'px';
lens.style.top = y + 'px';
result.style.backgroundPosition = `-${x * cx}px -${y * cy}px`;
}
function getCursorPos(e) {
let a = image.getBoundingClientRect();
return {
x: e.pageX - a.left - window.pageXOffset,
y: e.pageY - a.top - window.pageYOffset
};
}
image.addEventListener('mouseenter', () => {
lens.style.display = 'block';
result.style.display = 'block';
result.style.backgroundImage = `url(${image.src})`;
});
image.addEventListener('mouseleave', () => {
lens.style.display = 'none';
result.style.display = 'none';
});
});getCursorPos函数和moveLens函数中的计算逻辑,确保所有尺寸和位置的计算都是准确的。requestAnimationFrame来优化动画效果,减少不必要的DOM操作。通过以上步骤,你可以实现一个基本的鼠标放图片放大镜效果,并解决常见的问题。