Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JS for image magnifying glass effect (with source code)


May 29, 2021 Article blog



One of the most basic JS features we have when we browse the Mall's web pages is to zoom in on the product picture, also known as the image amplifier feature. W3Cschool is a small compilation to teach you how to use JS to achieve the picture magnifying glass effect.

Let's start with the implementation:

 JS for image magnifying glass effect (with source code)1

The full source code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>图片放大镜 - 编程狮(w3cschool.cn)</title>
	<style>
		* {
			margin:0px;
			padding:0px;
			}
		#left {
			width:350px;
			height:350px;
			float:left;
			border:1px solid #cccccc;
			margin-top:10px;
			margin-left:10px;
			position:relative;
			}
		#right {
			border:1px solid #cccccc;
			float:left;
			position:relative;
			width:350px;
			height:350px;
			display:none;
			overflow:hidden;
			margin-top:10px;
			}
		#right img {
			position:absolute;
			}
		#small {
			width:150px;
			height:150px;
			background-color:#F90;
			border:1px solid #cccccc;
			opacity:0.3;
			top:0px;
			position:absolute;
			cursor:move;
			display:none;
			}
		#left img {
			width:100%;
			height:100%;
			}
	</style>
</head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>
<script> $(document).ready(function(e) { $("#left").mousemove(move).mouseenter(function() { $("#small").show(); $("#right").show() }).mouseleave(function() { $("#small").hide(); $("#right").hide() }) }); function move(e) { var y = e.pageY - $("#left").offset().top; if (y >= 75 && y <= 275) { $("#small").css("top", y - 75); $("#right img").css("top", -(y - 75) * 800 / 350); } var x = e.pageX - $("#left").offset().left; if (x >= 75 && x <= 275) { $("#small").css("left", x - 75); $("#right img").css("left", -(x - 75) * 800 / 350); } } </script> <body> <div id="left"> <img src="./image/01.png"> <div id="small"></div> </div> <div id="right"> <img src="./image/01.png"> </div> </body> </html>

Photo footage:

 JS for image magnifying glass effect (with source code)2

Here's all the code and related footage for the picture amplifier effect with JS. Ask the students to practice and consolidate themselves.