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>
Copy after login

css code:

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

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);        }
Copy after login

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();        }
Copy after login

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);        }
Copy after login

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" }                );        }
Copy after login

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

How to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

How do I use the HTML5 <time> element to represent dates and times semantically? How do I use the HTML5 <time> element to represent dates and times semantically? Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 &lt;time&gt; element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

See all articles