Simple implementation of javascript magnifying glass effect

  • 2020-03-30 00:46:31
  • OfStack

It's not that hard to do, but the point is the position and the scale,

Capture the mouse position, determine the mouse position area, and the onmouseover, onmousemove, and onmouseout events

Set the scale of the display of the large picture, the small picture on the display of the proportion of the cut map should be accurate, the best is 2 times, 4 times.

Focus on the width. My picture here, m.pg is 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> Magnifying glass effect </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");//Filter images
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;
 //The above two variables indicate the areas where showimg allows activity
};
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;
 //To get the current moving showimg position the calculation method is the mouse coordinate - the coordinates of the outermost container - the width (height) of the box /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>


Related articles: