原生JavaScript实现的简单放大镜效果示例

编程学习 2021-07-04 17:33www.dzhlxh.cn编程入门
这篇文章主要介绍了原生JavaScript实现的简单放大镜效果,涉及javascript事件响应及页面元素属性动态操作相关实现技巧,需要的朋友可以参考下

本文实例讲述了原生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>

运行效果:

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《》

希望本文所述对大家JavaScript程序设计有所帮助。

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板