温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

原生js实现放大镜的示例分析

发布时间:2021-06-18 14:49:01 来源:亿速云 阅读:105 作者:小新 栏目:web开发

这篇文章主要介绍原生js实现放大镜的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

原理:左边阴影在左边图片上从左到右移动的时候,右边大框也在右边大图片上从左到右移动(尽管在视觉、原理和代码上是相反的);所谓放大,其实就是一张原本就很小的图对应一张原本就很大的图。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <style>
    *{
      margin:0;
      padding:0;
    }
    .small{
      width: 400px;
      height: 400px;
      position: relative;
      background: url(http://www.qdfuns.com/misc.php?mod=attach&genre=editor&aid=7dca2c442134be6a652e087296c8ac80) no-repeat center;
      border: 1px solid #ccc;
    }
    .small .inner{
      width: 100px;
      height: 100px;
      background: yellow;
      opacity: 0.5;
      filter: alpha(opacity=50);
      position: absolute;
      left:0;
      top:0;
      display: none;
    }
    .big{
      width: 400px;
      height: 400px;
      position: absolute;
      left:410px;
      top:0;
      overflow: hidden;
      border: 1px solid #ccc;
      display: none;
    }
    .big img{
      width: 200%;
      height: 200%;
      position: absolute;
      left:0;
      top:0;
    }
  </style>
</head>
<body>
<div id="small" class="small">
  <div class="inner"></div>
</div>
<div id="big" class="big">
  <img src="http://www.qdfuns.com/misc.php?mod=attach&genre=editor&aid=d7dec5aeff022ea80c47eb76dc5838d8" alt=""/>
</div>
<script>
  var small=document.getElementById('small');
  var inner=small.getElementsByTagName('div')[0];
  var big=document.getElementById('big');
  var img=big.getElementsByTagName('img')[0];
  //当鼠标移入small的时候,inner和big显示
  small.onmouseover=function(){
    big.style.display='block';
    inner.style.display='block';
  };
  //当鼠标在small移动的时候:1)鼠标在inner的中间 2)inner跟随鼠标移动
  small.onmousemove=function(e){
    e=e||window.event;
    var left=e.clientX-this.offsetLeft-inner.offsetWidth/2;
    var top=e.clientY-this.offsetTop-inner.offsetHeight/2;
    if(left<=0){
      left=0;
    }else if(left>=this.offsetWidth-inner.offsetWidth){
      left=this.offsetWidth-inner.offsetWidth
    }
    if(top<=0){
      top=0;
    }else if(top>=this.offsetHeight-inner.offsetHeight){
      top=this.offsetHeight-inner.offsetHeight
    }
    inner.style.left= left+'px';
    inner.style.top= top+'px';
    //当inner移动的时候,大图跟着一起移动,并且,大图和inner移动的方向相反;
    //或者理解为:左边阴影在图片上从左到右移动的时候,右边大框也在大图片上从左到右移动(尽管视觉上是相反的)。
    img.style.left=left/(small.offsetWidth-inner.offsetWidth)*(big.offsetWidth-img.offsetWidth)+'px';
    img.style.top=top/(small.offsetHeight-inner.offsetHeight)*(big.offsetHeight-img.offsetHeight)+'px';
  };
  //当鼠标移出的时候,inner和big隐藏;
  small.onmouseout=function(){
    big.style.display='none';
    inner.style.display='none';
  }
</script>
</body>
</html>

以上是“原生js实现放大镜的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI