本文详细介绍如何使用 JavaScript 实现图片放大镜效果。核心在于通过 onmouseover、onmousemove 和 onmouseout 事件捕获鼠标位置,计算小图与大图的比例关系,并动态调整显示区域的位置与背景坐标。文章提供了完整的 HTML/CSS/JS 示例代码,涵盖关键参数设置如 2 倍或 4 倍放大比例及边界限制逻辑,帮助开发者快速掌握该前端交互技巧。
JavaScript 实现图片放大镜效果的完整代码与原理
实现这一效果的核心在于精确控制显示区域的位置以及图片放大的比例。
需要重点处理鼠标位置的捕获、鼠标所在区域的判断,并合理使用 onmouseover、onmousemove 以及 onmouseout 这三个鼠标事件。
在设置显示大图的比例时,需确保小图中显示切图的比例准确无误,通常建议采用 2 倍或 4 倍的放大倍数。
需特别注意图片的宽度设置,例如示例中使用的图片 m.jpg 尺寸为 1440x900 像素。
具体实现代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>放大镜效果</title>
<style type="text/css">
*{margin:0;padding:0;}
#smallimg{width:360px;float:left;position:relative;border:1px solid red;}
#smallimg img{ width:360px;}
#bigimg{float:left;width:400px;height:400px;margin-left:40px;border:1px solid #ccc;display:none;}
#showimg{width:100px;height:100px;background:#fff;cursor:move; position:absolute;border:1px solid #666;opacity:0.5;filter:alpha(opacity=50);display:none;}
</style>
</head>
<body>
<div id="smallimg">
<img src="jq/m.jpg" alt=""/>
<div id="showimg"> </div>
</div>
<div id="bigimg"> </div>
<script type="text/javascript">
var $=function(id){return typeof id=="string"?document.getElementById(id):id}
var smallimg = $("smallimg");
var showimg = $("showimg");//滤镜图片
var bigimg = $("bigimg");
var small_url = smallimg.getElementsByTagName("img")[0].getAttribute("src");
var show_half = maxWidth = maxHeight = 0;
smallimg.onmouseover = function(){
showimg.style.display = "block";
bigimg.style.display = "inline";
show_half = showimg.offsetHeight/2;
maxWidth = smallimg.clientWidth - showimg.offsetWidth;
maxHeight = smallimg.clientHeight - showimg.offsetHeight;
//上面两个变量指明showimg允许活动的区域
};
smallimg.onmousemove = function(e){
var e=window.event?window.event:e;
var num=bigimg.clientWidth/showimg.clientWidth;
var Top = e.clientY - smallimg.offsetTop - show_half;
var Left = e.clientX - smallimg.offsetLeft - show_half;
//获取当前移动的showimg位置 计算方法是 鼠标坐标 - 最外面容器的坐标 - 盒子的宽(高)的/2
Top = Top<0?0:Top>maxHeight?maxHeight:Top;
Left = Left<0?0:Left>maxWidth?maxWidth:Left;
showimg.style.top = Top + "px";
showimg.style.left = Left + "px";
bigimg.style.background = "url("+small_url+") -"+Left*num+"px -"+Top*num+"px no-repeat";
};
smallimg.onmouseout = function(){
showimg.style.display="none";
bigimg.style.background ="";
bigimg.style.display="none"
};
</script>
</body>
</html>