Effect of Javascript imitating JD.COM magnifying glass

  • 2021-07-24 10:14:19
  • OfStack

Just find a picture. Dear friends, play as you want (pay attention to the path), and test it yourself. It's absolutely no problem.

Without saying much, please look at the code:


<html>
<head>
<meta charset="utf-8">
<style type="text/css">
body,div{margin: 0; padding: 0;}
#zhuti{ 
margin:50px;
position: relative;
}
#small{
width: 300px;
height: 187px;
border: 1px solid #000;
}
#big{
border: 1px solid #666;
overflow: hidden;
width: 300px;
height: 187px;
position: absolute;
left: 310px;
top: 0px;
display: none; /* Default hide */
}
#jingtou{
width: 50px;
height: 50px;
background: #666;
opacity: 0.4;
position: absolute;
display: none; /* Default hide */
}
#bigimg{
position: absolute;
}
</style>
</head>
<body>
<div id="zhuti">
<div id="small">
<div id="jingtou"></div>
<img src="img/ktm_small.jpg">
</div>
<div id="big">
<img src="img/ktm_big.jpg" id="bigimg">
</div>
</div>
<script type="text/JavaScript">
// Encapsulation 1 Functions (id Formal parameter )
function $(id) {
return document.getElementById(id);
}
var small =$('small');
var big =$('big');
var jingtou =$('jingtou');
var zhuti =$('zhuti');
var bigimg =$('bigimg');
// Monitor mouse ( Lens )
small.onmouseover = function(){
big.style.display='block';
jingtou.style.display='block';
}
small.onmouseout = function(){
big.style.display='none';
jingtou.style.display='none';
}
// When the rat baffle moves, 
small.onmousemove = function(event){
// Get the current coordinates  // Subtracting the lens width 1 Half 
var left = event.clientX - zhuti.offsetLeft -jingtou.offsetWidth/2;
var top = event.clientY -zhuti.offsetTop - jingtou.offsetHeight/2;
// Make judgment statement (fixed 0 Location of) 
// Go to the left 
if(left<=0){
left =0;
}
// Go up 
if(top<=0){
top =0;
}
// Go to the right 
if(left >= small.offsetWidth-jingtou.offsetWidth){
left = small.offsetWidth-jingtou.offsetWidth;
}
// Go down 
if(top >= small.offsetHeight-jingtou.offsetHeight){
top = small.offsetHeight-jingtou.offsetHeight;
}
// Scale of small figure 
var smallX = left / (small.offsetWidth - jingtou.offsetWidth);
//var smallX = left / (small.offsetWidth - jingtou.offsetWidth);
var smallY = top / (small.offsetHeight - jingtou.offsetHeight);
//var smallY = top / (small.offsetHeight - jingtou.offsetHeight);
var bigX = -smallX * (bigimg.offsetWidth - big.offsetWidth); 
var bigY = -smallY * (bigimg.offsetHeight - big.offsetHeight);
// Seek a And b Value of 
bigimg.style.left = bigX + 'px';
bigimg.style.top = bigY + 'px';
// Position of lens distance to the left == The position to the left of the mouse distance 
jingtou.style.left = left +'px';
jingtou.style.top = top +'px';
}
</script>
</body>
</html>

Related articles: