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
The Lost CSS Tricks of Cohost.orgThe Lost CSS Tricks of Cohost.orgApr 25, 2025 am 09:51 AM

In this post, Blackle Mori shows you a few of the hacks found while trying to push the limits of Cohost’s HTML support. Use these if you dare, lest you too get labelled a CSS criminal.

Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor