search
HomeWeb Front-endCSS TutorialDetailed explanation of the example of using css to achieve the picture magnifying glass effect (picture)

This article explains how to use css to achieve PictureMagnifying glass effect ? The following is a detailed explanation of the CSS example of the picture magnifying glass effect.

The effect is as shown in the figure (in the example, I secretly linked a picture of Tmall, I hope it’s okay-.-):

Detailed explanation of the example of using css to achieve the picture magnifying glass effect (picture)

The implementation process is simple, but we still start the analysis from css. The process is as follows (the picture is a square as an example):

css:

/* 图片容器 */
    .imgBox{
      width: 200px; /* 各位大老爷们看着办 */
      height: 200px; /* 各位大老爷们看着办 */
      position: relative; /* 必需 */
    }
 
    /* 图片标签 */
    .mainImg{
      width: 100%; /* 各位大老爷们看着办,尽量100%好看些[斜眼笑] */
      height: 100%; /* 各位大老爷们看着办,尽量100%好看些[斜眼笑] */
    }
 
    /* 遮罩层-既放大区域 */
    .glass{
      position: absolute; /* 必需 */
      width: 50px; /* 遮罩层宽度 此处是放大4倍,所以为200/4=50 */
      height: 50px; /* 遮罩层高度 此处是放大4倍,所以为200/4=50  */
      top: -9999px; /* 绝对位置,先放远些 */
      left: -9999px; /* 绝对位置,先放远些 */
      cursor: move; /* 鼠标样式,好看些 */
      background: rgba(0,0,180,0.5); /* 遮罩层样式,好看些 */
    }
 
    /* 大图所在的容器 */
    .imgMax{
      position: absolute;  /* 必需 */
      overflow: hidden; /* 必需,盖掉超出的大图[斜眼笑] */
      left: 210px; /* 必需,此处为距原图左边10像素 */
      top: 0; /* 必需,此处为距上边0像素 */
      width: 200px; /* 放大图片容器的宽度 此处此处是放大4倍,为200,保持和原图容器一般大,若此处为400,则是放大2*4倍,那么相应的放大图片应该是200*4*2=1600 */
      height: 200px; /* 放大图片容器的高度 此处此处是放大4倍,为200,保持和原图容器一般大,若此处为400,则是放大2*4倍,那么相应的放大图片应该是200*4*2=1600 */
      display: none; /* 先隐藏 */
    }
    .maxImg{
      position: absolute; /* 必需 */
      width: 800px; /* 此处是放大4倍,所以为200*4=800  受放大图片所在的容器影响,规则如上 */
      height: 800px; /* 此处是放大4倍,所以为200*4=800  受放大图片所在的容器影响,规则如上 */
    }

What you need to pay attention to in the above css are several positions and scaling ratios. Pay attention to the adjustments.

After writing the style, let’s take a look at the layout:

html:

<!-- 图片容器 -->
    <pclass>
      <!-- 需要放大的图片-原始图 -->
      <img  class="J_mainImg mainImg lazy" src="/static/imghwm/default1.png" data-src="http://img.alicdn.com/bao/uploaded/i7/TB1Xpe_NXXXXXXRXFXXGTq09XXX_035318.jpg_430x430q90.jpg" alt="Detailed explanation of the example of using css to achieve the picture magnifying glass effect (picture)" >
      <!-- 遮罩-既放大的区域 -->
      <pclass>
      <!-- 大图的容器 -->
      <pclass>
        <!-- 大图 -->
        <img  class="J_maxImg maxImg lazy" src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/164/92904c7f39f2e60a002ba228e687b2e8-1.png?x-oss-process=image/resize,p_40" alt="Detailed explanation of the example of using css to achieve the picture magnifying glass effect (picture)" >
      
    </pclass></pclass></pclass>

Next is the main js code, with comments as always:

js:

(function(){
    /* 放大镜函数
    ** @imgContainer  需要实现放大镜效果的图片容器  此处是 class 为 J_imgBox 的 p
    */
    function imgZoom(imgContainer){
 
      // 取大图url,不知道淘宝图片规则如何,反正看了详情页的大图和小图url对比,随便写了个替换
      var imgUrl = imgContainer.querySelector('.J_mainImg').src.replace(/.(jpg|jpeg|png|gif)(_)(d+)(x)(d+)(q90)?/g,'');
 
      // 取大图标签的节点
      var maxImg = imgContainer.querySelector('.J_maxImg');
 
      // 给该节点的src属性赋值为大图的url
      maxImg.src = imgUrl;
 
      // 取大图所在的容器
      var maxImgContainer = imgContainer.querySelector('.J_imgMax');
 
      // 取遮罩块
      var glassBlock = imgContainer.querySelector('.J_glass');
 
      // 取消放大镜效果
      var hideMaxImg = function(){
        glassBlock.style.top = '-9999px';
        glassBlock.style.left = '-9999px';
        maxImgContainer.style.display = 'none';
      }
 
      // 鼠标移出图片区域,取消放大镜效果
      imgContainer.onmouseout = function(event){
        event.stopPropagation();
        hideMaxImg();
      };
 
      // 鼠标在图片区域内移动事件
      imgContainer.onmousemove = function(event) {
        event.stopPropagation();
 
        // 取图片容器的大小及其相对于视口的位置,需要实时取,所以放在move事件里
        var clientRect = event.currentTarget.getBoundingClientRect();
 
        // 获取距鼠标距的上和左的坐标
        var leftX = event.clientX - clientRect.left;
        var leftY = event.clientY - clientRect.top;
 
        // 动态设置遮罩块的left和top位置  这里需要减去遮罩层的一半,因为鼠标位于遮罩块中心点
        var pointerLeft = leftX - 25;
        var pointerTop = leftY - 25;
 
        // 如果鼠标坐标移动超出原始图片区域边缘 则取消放大镜效果  因为这里存在快速移动鼠标到大图区域时,鼠标仍处在外层的图片区域内,并不会触发mouseout事件(虽然中间隔了小小的间距,但是快速移动仍能产生这个bug,如代码下面的图所示)
        if((pointerLeft+25) > clientRect.width || pointerLeft  clientRect.height || pointerTop ){
          hideMaxImg();
          return !1;
        };
 
        // 遮罩块在最左边的时候,鼠标仍在图片区域内,可在遮罩块左边缘至中心线区域内移动,且这时遮罩块为距左0像素
        if(pointerLeft ){
          pointerLeft = 0;
        };
 
        // 同上 右边限制
        if(pointerLeft > clientRect.width - 50){
          pointerLeft = clientRect.width - 50;
        };
 
        // 同上 顶部限制
        if(pointerTop ){
          pointerTop = 0;
        };
 
        // 同上 底部限制
        if(pointerTop > clientRect.height - 50){
          pointerTop = clientRect.height - 50;
        };
 
        // 设置遮罩块的位置
        glassBlock.style.left = pointerLeft;
        glassBlock.style.top = pointerTop;
 
        // 取遮罩快距离左边的位置和图片区域的宽高比,用于计算大图偏移距离,展示遮罩块所对应的图片区域
        var percentLeft = pointerLeft/clientRect.width;
        var percentHeight = pointerTop/clientRect.height;
 
        // 设置大图偏移距离 因为其父元素存在 overflow:hidden 所以只会展示对应区块
        maxImg.style.left = -(percentLeft*maxImg.clientWidth)+'px';
        maxImg.style.top = -(percentHeight*maxImg.clientHeight)+'px';
      };
    }
 
    var elem = document.querySelectorAll('.J_imgBox');
 
    elem.forEach(function(item,idx){
      imgZoom(item)
    })
  })()

bug fixing picture:

Detailed explanation of the example of using css to achieve the picture magnifying glass effect (picture)

After reading this, do you feel that it is not too simple? Next, let’s take a look at the more practical knowledge points that can be extracted from the above code in daily development:

Element .getBoundingClientRect()

Element.getBoundingClientRect() method returns the size of the element and its position relative to the viewport

Example:

<bodystyle>
      <pid>
      <script>
        (function(){
          var elem = document.getElementById(&#39;testp&#39;);
          document.body.addEventListener(&#39;click&#39;,function(){
              console.log(elem.getBoundingClientRect())
          },false)
        })()
      </script>
    </pid></bodystyle>

The above is the detailed content of Detailed explanation of the example of using css to achieve the picture magnifying glass effect (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Anchor Positioning Just Don't Care About Source OrderAnchor Positioning Just Don't Care About Source OrderApr 29, 2025 am 09:37 AM

The fact that anchor positioning eschews HTML source order is so CSS-y because it's another separation of concerns between content and presentation.

What does margin: 40px 100px 120px 80px signify?What does margin: 40px 100px 120px 80px signify?Apr 28, 2025 pm 05:31 PM

Article discusses CSS margin property, specifically "margin: 40px 100px 120px 80px", its application, and effects on webpage layout.

What are the different CSS border properties?What are the different CSS border properties?Apr 28, 2025 pm 05:30 PM

The article discusses CSS border properties, focusing on customization, best practices, and responsiveness. Main argument: border-radius is most effective for responsive designs.

What are CSS backgrounds, list the properties?What are CSS backgrounds, list the properties?Apr 28, 2025 pm 05:29 PM

The article discusses CSS background properties, their uses in enhancing website design, and common mistakes to avoid. Key focus is on responsive design using background-size.

What are CSS HSL Colors?What are CSS HSL Colors?Apr 28, 2025 pm 05:28 PM

Article discusses CSS HSL colors, their use in web design, and advantages over RGB. Main focus is on enhancing design and accessibility through intuitive color manipulation.

How can we add comments in CSS?How can we add comments in CSS?Apr 28, 2025 pm 05:27 PM

The article discusses the use of comments in CSS, detailing single-line and multi-line comment syntaxes. It argues that comments enhance code readability, maintainability, and collaboration, but may impact website performance if not managed properly.

What are CSS Selectors?What are CSS Selectors?Apr 28, 2025 pm 05:26 PM

The article discusses CSS Selectors, their types, and usage for styling HTML elements. It compares ID and class selectors and addresses performance issues with complex selectors.

Which type of CSS holds the highest priority?Which type of CSS holds the highest priority?Apr 28, 2025 pm 05:25 PM

The article discusses CSS priority, focusing on inline styles having the highest specificity. It explains specificity levels, overriding methods, and debugging tools for managing CSS conflicts.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.