App下載

JS實現(xiàn)圖片放大鏡效果(附源碼)

猿友 2021-03-16 14:34:06 瀏覽數(shù) (4655)
反饋

我們在瀏覽商城網(wǎng)頁時,有一個最基本的 JS 功能就是將商品圖片進行放大,也稱圖片放大器功能。W3Cschool 小編就來教大家如何用JS實現(xiàn)圖片放大鏡效果。

我們先來看下實現(xiàn)效果:

JS實現(xiàn)圖片放大鏡效果

完整源碼如下:

<!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>

圖片素材:

JS實現(xiàn)圖片放大器效果

以上就是用 JS 實現(xiàn)圖片放大器效果的全部代碼及相關素材。請同學們自行練習和鞏固噢。


0 人點贊