以下是一个简单的JavaScript放大镜效果的实现代码示例:
一、HTML结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>放大镜效果</title>
<style>
/* 样式部分后续补充 */
</style>
</head>
<body>
<div class="img-magnifier-container">
<img id="myimage" src="your - image - url.jpg" width="600" height="400">
<div id="myresult" class="magnifier"></div>
</div>
<script>
// JavaScript代码后续补充
</script>
</body>
</html>
二、CSS样式
.img - magnifier - container {
position: relative;
}
.magnifier {
position: absolute;
border: 3px solid #000;
border-radius: 50%;
cursor: none;
/* 默认隐藏放大镜 */
display: none;
/* 放大镜大小 */
width: 100px;
height: 100px;
/* 背景色半透明 */
background - repeat: no - repeat;
/* 调整背景缩放比例以显示放大效果 */
background - size: 1200px 800px;
}
三、JavaScript代码
window.onload = function () {
const img = document.getElementById('myimage');
const magnifier = document.getElementById('myresult');
magnifier.addEventListener('mousemove', moveMagnifier);
img.addEventListener('mousemove', moveMagnifier);
img.addEventListener('mouseleave', hideMagnifier);
function moveMagnifier(e) {
const imgRect = img.getBoundingClientRect();
const magnifierWidth = magnifier.offsetWidth / 2;
const magnifierHeight = magnifier.offsetHeight / 2;
let x = e.pageX - imgRect.left - window.pageXOffset - magnifierWidth;
let y = e.pageY - imgRect.top - window.pageYOffset - magnifierHeight;
if (x < 0) {
x = 0;
} else if (x > img.width - magnifier.offsetWidth) {
x = img.width - magnifier.offsetWidth;
}
if (y < 0) {
y = 0;
} else if (y > img.height - magnifier.offsetHeight) {
y = img.height - magnifier.offsetHeight;
}
magnifier.style.left = x + 'px';
magnifier.style.top = y + 'px';
magnifier.style.backgroundImage = 'url("' + img.src + '")';
magnifier.style.backgroundSize = (img.width * 2) + 'px ' + (img.height * 2) + 'px';
magnifier.style.backgroundPosition = '-' + (x * 2) + 'px -' + (y * 2) + 'px';
magnifier.style.display = 'block';
}
function hideMagnifier() {
magnifier.style.display = 'none';
}
};
1. 基础概念
div
)的位置和背景显示内容。放大镜元素的背景设置为原始图片,并且根据鼠标位置调整背景的偏移量来显示放大部分。
2. 优势如果在实现过程中遇到问题: 一、放大镜不显示
display: none;
没有正确修改为display: block;
。检查JavaScript中关于显示放大镜的逻辑,确保在鼠标移动到图片上时正确修改了这个属性。src
路径可能错误,导致放大镜背景设置失败。moveMagnifier
函数中添加调试语句,如console.log
来查看是否进入了显示放大镜的分支。二、放大镜位置不正确
领取专属 10元无门槛券
手把手带您无忧上云