Home Web Front-end HTML Tutorial js-magnifying glass effect_html/css_WEB-ITnose

js-magnifying glass effect_html/css_WEB-ITnose

Jun 24, 2016 am 11:48 AM

JD or Taobao’s specific products have a magnifying glass effect. Although there are many similar plug-ins on the Internet, there are many inconveniences in applying them to projects. If you take some time to write a similar plug-in yourself and accumulate the code, why not do it!! let'go:

  1. I plan to encapsulate this special effect into a plug-in. First implement the most basic algorithm, and then encapsulate it step by step:

Final effect:

html code:

<div id="Magnifier"></div>

css code:

 <style>        * {            margin: 0;            padding: 0;        }    </style>

It seems there is nothing, let’s start with our powerful js journey:

javascript code:

  function createElement(MagnifierId, sImg, bImg) {            var Magnifier = $(MagnifierId);            Magnifier.style.position = 'relative';            //小图div            var smallDiv = $Create("div");            smallDiv.setAttribute("id", "small");            smallDiv.style.position = "absolute";                       //遮罩层            var mask = $Create("div");            mask.setAttribute("id", "mask");            mask.style.position = "absolute";            //镜片            var mirror = $Create("div");            mirror.setAttribute("id", "mirror");            mirror.style.opacity = 0.3;            mirror.style.position = "absolute";            mirror.style.display = "none";            //小图            var smallImg = $Create("img");            smallImg.setAttribute("src", sImg);            smallImg.setAttribute("id", "smallImg");            smallImg.onload = function () {                //如果没设置放大镜的height或者width 根据小图大小设置放大镜大小                if (!Magnifier.offsetHeight) {                    Magnifier.style.width = this.offsetWidth+"px";                    Magnifier.style.height = this.offsetHeight + "px";                }                //遮罩层大小和小图一样                mask.style.opacity = "0";                mask.style.width = this.width + 'px';                mask.style.height = this.height + "px";                mask.style.zIndex = 2;                bigDiv.style.left = this.width + 5 + "px";                bigDiv.style.top = "-5px";            }            smallDiv.appendChild(mask);            smallDiv.appendChild(mirror);            smallDiv.appendChild(smallImg);            //视窗            var bigDiv = $Create("div");            bigDiv.setAttribute("id", "big");            bigDiv.style.position = "absolute";            bigDiv.style.overflow = "hidden";            bigDiv.style.display = "none";            var bigImg = $Create("img");            bigImg.setAttribute("src", bImg);            bigImg.setAttribute("id", "bigImg");            bigImg.style.position = "absolute";            bigDiv.appendChild(bigImg);            Magnifier.appendChild(smallDiv);            Magnifier.appendChild(bigDiv);        }        function setMagnifierStyle(mirrorStyle,shichuangStyle) {                            //mirror            for (var item in mirrorStyle) {                mirror.style[item] = mirrorStyle[item];            }            for (var item in shichuangStyle) {                $("big").style[item] = shichuangStyle[item];            }                   }        function registerEvent() {            $("mask").onmouseover = function () {                $("big").style.display = "block";                mirror.style.display = "block";            }            $("mask").onmouseout = function () {                $("big").style.display = "none";                mirror.style.display = "none";            }            $("mask").onmousemove = function (evt) {                var oEvent = evt || event;                var disX = oEvent.offsetX;                var disY = oEvent.offsetY;                var mirrorLeft = disX - mirror.offsetWidth / 2;                var mirrorTop = disY - mirror.offsetHeight / 2;                if (mirrorLeft < 0) {                    mirrorLeft = 0;                }                else if (mirrorLeft > mask.offsetWidth - mirror.offsetWidth) {                    mirrorLeft = mask.offsetWidth - mirror.offsetWidth;                }                if (mirrorTop < 0) {                    mirrorTop = 0;                }                else if (mirrorTop > mask.offsetHeight - mirror.offsetHeight) {                    mirrorTop = mask.offsetHeight - mirror.offsetHeight;                }                mirror.style.top = mirrorTop + "px";                mirror.style.left = mirrorLeft + "px";                var paX = mirrorTop / (mask.offsetHeight - mirror.offsetHeight);                var paY = mirrorLeft / (mask.offsetWidth - mirror.offsetWidth);                $("bigImg").style.top = -paX * ($("bigImg").offsetHeight - $("big").offsetHeight) + "px";                $("bigImg").style.left = -paY * ($("bigImg").offsetWidth - $("big").offsetWidth) + "px";            }        }        function $(id) {            return document.getElementById(id);        }        function $Create(type) {            return document.createElement(type);        }

Finally, make a small onload call:

 window.onload = function () {            createElement("Magnifier", "images/Magnifier/small.jpg", "images/Magnifier/big.jpg");            setMagnifierStyle({ "width": "30px", "height": "30px", "backgroundColor": "#fff" }, { "width": "250px", "height": "250px" });            registerEvent();        }

The effect is finally out,

2. Next let’s encapsulate:

Magnifer class code:

        function Magnifier(            MagnifierId,                            //放大镜容器ID            sImg,                                   //小图片src            bImg,                                   //大图片src            mirrorStyle,                            //小图片里镜片样式,json格式数据            ViewStyle                               //预览视窗样式,json格式数据            ) {            var _this = this;            this.MagnifierContainer = null;         //容器            this.smallDiv = null;                   //小图容器            this.mask = null;                       //小图遮罩层            this.mirror = null;                     //小图镜片            this.smallImg = null;                   //小图            this.bigDiv = null;                     //预览视图            this.bigImg = null;                     //大图            var init = function () {                _this.MagnifierContainer = _this.$(MagnifierId);                _this.createElement(sImg, bImg);                _this.setMagnifierStyle(mirrorStyle, ViewStyle);                _this.MainEvent();            }            init();        }        Magnifier.prototype.createElement = function (sImg, bImg) {            var _this = this;            var $Create = this.$Create;            this.MagnifierContainer.style.position = 'relative';   //脱离文档流,视情况修改            this.smallDiv = $Create("div");            this.smallDiv.setAttribute("id", "small");            this.smallDiv.style.position = "absolute";            this.mask = $Create("div");            this.mask.setAttribute("id", "mask");            this.mask.style.position = "absolute";            this.mirror = $Create("div");            this.mirror.setAttribute("id", "mirror");            this.mirror.style.opacity = 0.3;            this.mirror.style.position = "absolute";            this.mirror.style.display = "none";            this.smallImg = $Create("img");            this.smallImg.setAttribute("src", sImg);            this.smallImg.setAttribute("id", "smallImg");            this.smallImg.onload = function () {                //如果没设置放大镜的height或者width 根据小图大小设置放大镜大小                if (!_this.MagnifierContainer.offsetHeight) {                    _this.MagnifierContainer.style.width = this.offsetWidth + "px";                    _this.MagnifierContainer.style.height = this.offsetHeight + "px";                }                //遮罩层大小和小图一样                _this.mask.style.opacity = "0";                _this.mask.style.width = this.offsetWidth + 'px';                _this.mask.style.height = this.offsetHeight + "px";                _this.mask.style.zIndex = 2;                _this.bigDiv.style.left = this.offsetWidth + 5 + "px";                _this.bigDiv.style.top = "-5px";            }            this.smallDiv.appendChild(this.mask);            this.smallDiv.appendChild(this.mirror);            this.smallDiv.appendChild(this.smallImg);            this.bigDiv = $Create("div");            this.bigDiv.setAttribute("id", "big");            this.bigDiv.style.position = "absolute";            this.bigDiv.style.overflow = "hidden";            this.bigDiv.style.display = "none";            this.bigImg = $Create("img");            this.bigImg.setAttribute("src", bImg);            this.bigImg.setAttribute("id", "bigImg");            this.bigImg.style.position = "absolute";            this.bigDiv.appendChild(this.bigImg);            this.MagnifierContainer.appendChild(this.smallDiv);            this.MagnifierContainer.appendChild(this.bigDiv);        }        Magnifier.prototype.setMagnifierStyle = function (mirrorStyle, ViewStyle) {            for (var item in mirrorStyle) {                this.mirror.style[item] = mirrorStyle[item];            }            delete item;            for (var item in ViewStyle) {                this.bigDiv.style[item] = ViewStyle[item];            }        }        Magnifier.prototype.MainEvent = function () {            var _this = this;            this.mask.onmouseover = function () {                _this.bigDiv.style.display = "block";                _this.mirror.style.display = "block";            }            this.mask.onmouseout = function () {                _this.bigDiv.style.display = "none";                _this.mirror.style.display = "none";            }            this.mask.onmousemove = function (evt) {                var oEvent = evt || event;                var disX = oEvent.offsetX || oEvent.layerX;  //兼容ff                var disY = oEvent.offsetY || oEvent.layerY;                var mirrorLeft = disX - _this.mirror.offsetWidth / 2;                var mirrorTop = disY - _this.mirror.offsetHeight / 2;                if (mirrorLeft < 0) {                    mirrorLeft = 0;                }                else if (mirrorLeft > this.offsetWidth - _this.mirror.offsetWidth) {                    mirrorLeft = this.offsetWidth - mirror.offsetWidth;                }                if (mirrorTop < 0) {                    mirrorTop = 0;                }                else if (mirrorTop > this.offsetHeight - _this.mirror.offsetHeight) {                    mirrorTop = this.offsetHeight - _this.mirror.offsetHeight;                }                _this.mirror.style.top = mirrorTop + "px";                _this.mirror.style.left = mirrorLeft + "px";                var paX = mirrorTop / (this.offsetHeight - _this.mirror.offsetHeight);                var paY = mirrorLeft / (this.offsetWidth - _this.mirror.offsetWidth);                _this.bigImg.style.top = -paX * (_this.bigImg.offsetHeight - _this.bigDiv.offsetHeight) + "px";                _this.bigImg.style.left = -paY * (_this.bigImg.offsetWidth - _this.bigDiv.offsetWidth) + "px";            }        }        Magnifier.prototype.$ = function (id) {            return document.getElementById(id);        }        Magnifier.prototype.$Create = function (type) {            return document.createElement(type);        }

Finally under the onload call:

window.onload = function () {            new Magnifier(                        "Magnifier",                        "images/Magnifier/small.jpg",                        "images/Magnifier/big.jpg",                        { "width": "30px", "height": "30px", "backgroundColor": "#fff" },                        { "width": "250px", "height": "250px" }                );        }

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1503
276
Configuring Document Metadata Within the HTML head Element Configuring Document Metadata Within the HTML head Element Jul 09, 2025 am 02:30 AM

Metadata in HTMLhead is crucial for SEO, social sharing, and browser behavior. 1. Set the page title and description, use and keep it concise and unique; 2. Add OpenGraph and Twitter card information to optimize social sharing effects, pay attention to the image size and use debugging tools to test; 3. Define the character set and viewport settings to ensure multi-language support is adapted to the mobile terminal; 4. Optional tags such as author copyright, robots control and canonical prevent duplicate content should also be configured reasonably.

HTML for email templates tutorial HTML for email templates tutorial Jul 10, 2025 pm 02:01 PM

How to make HTML mail templates with good compatibility? First, you need to build a structure with tables to avoid using div flex or grid layout; secondly, all styles must be inlined and cannot rely on external CSS; then the picture should be added with alt description and use a public URL, and the buttons should be simulated with a table or td with background color; finally, you must test and adjust the details on multiple clients.

Best HTML tutorial for beginners in 2025 Best HTML tutorial for beginners in 2025 Jul 08, 2025 am 12:25 AM

TolearnHTMLin2025,chooseatutorialthatbalanceshands-onpracticewithmodernstandardsandintegratesCSSandJavaScriptbasics.1.Prioritizehands-onlearningwithstep-by-stepprojectslikebuildingapersonalprofileorbloglayout.2.EnsureitcoversmodernHTMLelementssuchas,

How to handle forms submission in HTML without a server? How to handle forms submission in HTML without a server? Jul 09, 2025 am 01:14 AM

When there is no backend server, HTML form submission can still be processed through front-end technology or third-party services. Specific methods include: 1. Use JavaScript to intercept form submissions to achieve input verification and user feedback, but the data will not be persisted; 2. Use third-party serverless form services such as Formspree to collect data and provide email notification and redirection functions; 3. Use localStorage to store temporary client data, which is suitable for saving user preferences or managing single-page application status, but is not suitable for long-term storage of sensitive information.

What are the most commonly used global attributes in html? What are the most commonly used global attributes in html? Jul 10, 2025 am 10:58 AM

class, id, style, data-, and title are the most commonly used global attributes in HTML. class is used to specify one or more class names to facilitate style setting and JavaScript operations; id provides unique identifiers for elements, suitable for anchor jumps and JavaScript control; style allows for inline styles to be added, suitable for temporary debugging but not recommended for large-scale use; data-properties are used to store custom data, which is convenient for front-end and back-end interaction; title is used to add mouseover prompts, but its style and behavior are limited by the browser. Reasonable selection of these attributes can improve development efficiency and user experience.

Implementing Native Lazy Loading for Images in HTML Implementing Native Lazy Loading for Images in HTML Jul 12, 2025 am 12:48 AM

Native lazy loading is a built-in browser function that enables lazy loading of pictures by adding loading="lazy" attribute to the tag. 1. It does not require JavaScript or third-party libraries, and is used directly in HTML; 2. It is suitable for pictures that are not displayed on the first screen below the page, picture gallery scrolling add-ons and large picture resources; 3. It is not suitable for pictures with first screen or display:none; 4. When using it, a suitable placeholder should be set to avoid layout jitter; 5. It should optimize responsive image loading in combination with srcset and sizes attributes; 6. Compatibility issues need to be considered. Some old browsers do not support it. They can be used through feature detection and combined with JavaScript solutions.

How to add a video as a background in HTML? How to add a video as a background in HTML? Jul 08, 2025 am 12:03 AM

To add a video background to a web page, the key is to use HTML tags correctly and optimize relevant attributes. 1. Use tags as background and use CSS positioning to fill the page or local area; 2. The video format is preferred.mp4, and WebM is added to consider compatibility; 3. Add muted and playsinline attributes to ensure automatic playback on the mobile side; 4. Control the video size to optimize the loading speed, and it is recommended to keep it at tens of MB; 5. Add loops to achieve seamless loop playback; 6. It can be flexibly applied to full screen or local blocks, and different effects are achieved by adjusting the container size and positioning method. The above steps can achieve a stable and beautiful video background.

How to make a responsive iframe? How to make a responsive iframe? Jul 09, 2025 am 01:39 AM

To make iframes responsive, the core is to use CSS to control the aspect ratio and combine it with the wrapping container to achieve adaptation. 1. Use padding techniques to create container boxes with fixed proportions. Common ratios such as 16:9 correspond to padding-top56.25%, 4:3 correspond to 75%, and 1:1 correspond to 100%; 2. Set the iframe width to 100% and use absolute positioning to fill the container, or use the aspect-ratio attribute to maintain the proportion; 3. When processing third-party embedded content, control the ratio through container wrapping, and ensure that the allowfullscreen attribute is added to support full-screen playback on mobile terminals. Master the container and proportion settings to realize the responsiveness of the iframe

See all articles