图片放大镜特效是一种常见的前端交互效果,它允许用户在查看图片时,通过移动鼠标或触摸屏幕来查看图片的放大区域。这种效果通常用于电商网站的产品展示、地图应用等场景,以提高用户体验和产品的细节展示。
图片放大镜特效通过以下几个步骤实现:
以下是一个简单的图片放大镜特效的JavaScript实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片放大镜特效</title>
<style>
.img-magnifier-container {
position: relative;
}
.magnifier {
position: absolute;
border: 3px solid #000;
border-radius: 50%;
cursor: none;
display: none;
z-index: 10;
}
.magnifier img {
position: absolute;
border-radius: 50%;
display: none;
}
</style>
</head>
<body>
<div class="img-magnifier-container">
<img id="myimage" src="your-image.jpg" width="600" height="400">
<div class="magnifier" id="magnifier"></div>
</div>
<script>
const img = document.getElementById('myimage');
const magnifier = document.getElementById('magnifier');
magnifier.style.width = '100px';
magnifier.style.height = '100px';
const imgWidth = img.width;
const imgHeight = img.height;
const magnifierWidth = magnifier.offsetWidth / 2;
const magnifierHeight = magnifier.offsetHeight / 2;
img.addEventListener('mousemove', moveMagnifier);
img.addEventListener('mouseleave', hideMagnifier);
function moveMagnifier(e) {
const x = e.pageX - img.offsetLeft - magnifierWidth;
const y = e.pageY - img.offsetTop - magnifierHeight;
if (x > imgWidth - magnifierWidth * 2) { x = imgWidth - magnifierWidth * 2; }
if (x < magnifierWidth) { x = magnifierWidth; }
if (y > imgHeight - magnifierHeight * 2) { y = imgHeight - magnifierHeight * 2; }
if (y < magnifierHeight) { y = magnifierHeight; }
magnifier.style.left = x + 'px';
magnifier.style.top = y + 'px';
magnifier.style.display = 'block';
const bgX = -x * 2;
const bgY = -y * 2;
magnifier.style.backgroundImage = `url('${img.src}')`;
magnifier.style.backgroundSize = (imgWidth * 2) + 'px ' + (imgHeight * 2) + 'px';
magnifier.style.backgroundPosition = `${bgX}px ${bgY}px`;
}
function hideMagnifier() {
magnifier.style.display = 'none';
}
</script>
</body>
</html>
position
和display
属性。background-size
和background-position
的计算方式,以适应不同的放大倍数需求。通过以上示例和解释,你可以实现一个基本的图片放大镜特效,并根据需要进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云