图片局部放大是一种常见的前端交互效果,允许用户通过鼠标悬停在图片的特定区域来查看该区域的放大视图。这种效果通常通过CSS和JavaScript来实现。
以下是一个简单的JavaScript实现示例,使用CSS和JavaScript来实现图片局部放大效果。
<div class="magnifier">
<img src="path/to/image.jpg" alt="Image" id="magnifier-image">
<div class="magnifier-lens" id="magnifier-lens"></div>
<div class="magnifier-result" id="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;
display: none;
}
.magnifier-result {
position: absolute;
top: 0;
right: -100%;
width: 300px;
height: 300px;
border: 1px solid #000;
background-repeat: no-repeat;
display: none;
}
document.addEventListener('DOMContentLoaded', function() {
const image = document.getElementById('magnifier-image');
const lens = document.getElementById('magnifier-lens');
const result = document.getElementById('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
};
}
image.addEventListener('mouseenter', () => {
lens.style.display = 'block';
result.style.display = 'block';
result.style.backgroundImage = `url(${image.src})`;
result.style.backgroundSize = `${image.width * cx}px ${image.height * cy}px`;
});
image.addEventListener('mouseleave', () => {
lens.style.display = 'none';
result.style.display = 'none';
});
});
requestAnimationFrame
来优化动画效果,减少DOM操作。通过以上方法,可以实现一个简单且高效的图片局部放大效果。
企业创新在线学堂
腾讯云存储知识小课堂
云+社区技术沙龙[第17期]
DB・洞见
新知
云+未来峰会
云+社区技术沙龙[第7期]
云+社区技术沙龙[第14期]
领取专属 10元无门槛券
手把手带您无忧上云