原生javascript 简易实现放大镜效果

原理: 其实所谓的放大就是准备两张一样的图片,除大小不一样。鼠标移动到不同位置,将会显示大图片对应的图片内容。


<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>放大镜效果</title>
</head>
<body>
	<div id="wrap" style="position: relative;width: 900px;margin: 0 auto;text-align: center;">
		<div id="smallImg" style="width: 400px;height: 400px; position: relative;z-index: 1;">
			<img src="small.jpg" style="width: 400px;height: 400px;"/>
			<span id="filter"  style="width: 200px;height: 200px;background-color: blue;opacity: 0.1;position: absolute;top: 0;left: 0; z-index: 2;cursor: move;display: none;">
			<span>
		</div>
		<div id="bigImg" style="width: 400px;height: 400px;overflow: hidden;position: absolute;right: 0px;top: 0;display: none;">
			<img src="large.jpg" style="width: 800px;height:800px; position: absolute;left: 0;top: 0;">
		</div>
		
	</div>
	<script type="text/javascript">
		var filter = document.getElementById('filter');
		var smallImg = document.getElementById('smallImg');
		var bigImg = document.getElementById('bigImg');	
		var wrap = document.getElementById('wrap');
		var largeImgs = bigImg.getElementsByTagName('img')[0];

		smallImg.onmouseover = function(){
			bigImg.style.display = "inline-block";
			filter.style.display = "inline-block";
		}

		smallImg.onmousemove = function(event){
			var event = event || window.event;
			var mouseleft = event.clientX - wrap.offsetLeft;
			var mousetop = event.clientY - wrap.offsetTop;
			var left = mouseleft<smallImg.offsetWidth/4?0:mouseleft>smallImg.offsetWidth*3/4?smallImg.offsetWidth/2:(mouseleft - filter.offsetWidth/2);
			var top = mousetop<smallImg.offsetHeight/4?0:mousetop>smallImg.offsetHeight*3/4?smallImg.offsetHeight/2:(mousetop - filter.offsetWidth/2);
			filter.style.left = left + "px";
			filter.style.top = top +"px"; 
			largeImgs.style.left = "-" + left*bigImg.offsetWidth/smallImg.offsetWidth + "px";
			largeImgs.style.top = "-" + top*bigImg.offsetHeight/smallImg.offsetHeight + "px";
		}
		smallImg.onmouseout = function(){
			bigImg.style.display = "none";
			filter.style.display = "none";
		}
	</script>
</body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值