要使用JavaScript实现放大镜效果,你需要理解几个基础概念:
<div class="magnifier">
<img src="path_to_image.jpg" alt="Image" id="original-image">
<div class="magnifier-lens"></div>
<div class="magnifier-result"></div>
</div>
.magnifier {
position: relative;
display: inline-block;
}
.magnifier-lens {
position: absolute;
border: 1px solid #000;
width: 100px; /* 放大镜宽度 */
height: 100px; /* 放大镜高度 */
background-color: rgba(255, 255, 255, 0.5);
pointer-events: none; /* 防止放大镜干扰鼠标事件 */
}
.magnifier-result {
position: absolute;
top: 0;
right: -100%; /* 放大结果显示在原始图像右侧 */
width: 300px; /* 放大结果宽度 */
height: 300px; /* 放大结果高度 */
border: 1px solid #000;
overflow: hidden;
}
document.addEventListener('DOMContentLoaded', function() {
const image = document.getElementById('original-image');
const lens = document.querySelector('.magnifier-lens');
const result = document.querySelector('.magnifier-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
};
}
result.style.backgroundImage = `url(${image.src})`;
result.style.backgroundSize = `${image.width * cx}px ${image.height * cy}px`;
});
moveLens
函数中的坐标计算准确无误。backgroundSize
的计算方式,确保放大后的图像清晰。通过以上步骤,你可以实现一个基本的放大镜效果。根据具体需求,还可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云