JavaScript object-oriented implementation of magnifying glass case

JavaScript object-oriented implementation of magnifying glass case

This article shares the specific code of JavaScript object-oriented implementation of magnifying glass for your reference. The specific content is as follows

Rendering

Implementation principle analysis

As shown in the figure

When the mouse move event is triggered, the real-time coordinates x and y are obtained according to the clientX and clientY properties of the event object.
Value, minus the offsetLeft value of small_box and half of the width of cutting_box , you can get the offset left value of cutting_box, and the same goes for the top value. When cutting_box reaches the right and bottom sides, left and top reach their maximum values. By comparing the real-time changing left and top values ​​with their respective maximum values, we can get a ratio , and then use this ratio to calculate the left and top of the big_img element on the right. The specific method is: first find out the width and height of big_img after enlargement, and then use this width and height to get the maximum value of the left and top of big_img. Multiplying this maximum value by the above ratio value will give the corresponding left and top values ​​of big_img.
Note: How to calculate the width and height of big_img after enlarging it
small_box width and height / cutting_box = big_img width and height / big_box width and height. (Only big_img width and height are unknown)

Basic page structure

<div class="small">
 <img src="images/timg.jpg" alt="">
 <span class="grayBox"></span>
</div>
<div class="big">
 <img src="images/timg.jpg" alt="">
</div>

CSS Code

.small {
 width: 400px;
 height: 400px;
 position: relative;
 border:4px solid #ddd;
 box-shadow: 0 0 5px rgba(0,0,0,.5);
}
.small img{
 width: 100%;
 height: 100%;
}
.small .grayBox{
 display: none;
 width: 100px;
 height: 100px;
 box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
 position: absolute;
 left: 0;
 top: 0;
} 
.big{
 width: 400px;
 height: 400px;
 position: absolute;
 left: 700px;
 top: 100px;
 border:1px solid #f10;
 display: none;
 overflow: hidden;
}
.bigimg{
 position: absolute;
}

Object-oriented implementation

Analysis (OOA)

  • Element selection function
  • Binding event driver
  • Show and hide elements
  • Small picture moves, large picture zooms in and follows the movement function
  • Mouse wheel zoom function

Design (OOD)

Constructor

function Magnifier(){}

Initialize each functional module

function init(){}

Event Binding Function

function bindEvent(){}

Show and hide elements

function eleToggle(){}

Small picture moves, large picture zooms in and follows function

function eleMove(){}

Writing (OOP)

  • First of all, it is clear that all functions should be placed on the prototype of the magnifying glass constructor.
  • Secondly, when instantiating an object, the parameter of the object type should be passed in, as shown below:
new Magnifier({
 small_box : ".small",
 cutting_box : ".grayBox",
 big_box : ".big",
 big_img : ".big img"
});

The constructor now needs to receive the parameters passed in during instantiation:

function Magnifier( options ) {
 // Call the initialization function to process the received parameter object this.init( options );
}

The initialization function completes the initialization elements and obtains the values ​​of the offset series of small_box, cutting_box, and big_box:

Magnifier.prototype.init = function( options ){
 // Initialize elements;
 for(var attr in options){
  this[attr+"_ele"] = this.$(options[attr]);
 }
 // In order to save performance, only get offsetLeft once;
 this.small_box_offset = {
  left : this.small_box_ele.offsetLeft,
  top : this.small_box_ele.offsetTop,
  width : parseInt( getComputedStyle(this.small_box_ele).width ),
  height : parseInt( getComputedStyle(this.small_box_ele).width )
 }
 this.cutting_box_offset = {
  width : parseInt( getComputedStyle(this.cutting_box_ele).width ),
  height : parseInt( getComputedStyle(this.cutting_box_ele).height ),
 }
 this.big_box_offset = {
  width : parseInt( getComputedStyle(this.big_box_ele).width ),
  height : parseInt( getComputedStyle(this.big_box_ele).height ),
 }
 // Flag variable, whether the mouse moves into the magnifying glass this.magnifier_start = false;
 this.bindEvent();
 // Image scaling function this.scaleBigImg();
}

Select element function:

Magnifier.prototype.$ = function(selector){
 return document.querySelector(selector);
}

Event binding function:

Magnifier.prototype.bindEvent = function(){
 //Move the mouse into the small_box on the left
 this.small_box_ele.addEventListener( "mouseover" , function(){
  // cutting_box big_box element display;
  this.eleToggle("show");
  // Change the flag variable to true
  this.magnifier_start = true;
  // Modify the this in the event function to point to the current instance object}.bind(this));
 //Mouse moves out of the small_box on the left
 this.small_box_ele.addEventListener( "mouseout" , function(){
  // cutting_box big_box element is hidden;
  this.eleToggle("hide");
  this.magnifier_start = false;
 }.bind(this));
 // Mouse moves, element moves;
 this.small_box_ele.addEventListener("mousemove" , function( evt ){
  var e = evt || event;
  // Get the xy value of the mouse point from the browser's visible area var x = e.clientX;
  var y = e.clientY ;
  // Call factoryPosition to get the coordinate value this.res = this.factoryPosition( x , y );
  // Pass the processed coordinate values ​​to the eleMove method and change the corresponding left and top values ​​this.eleMove( this.res );
 }.bind(this)); 
 // Scroll wheel event;
 document.addEventListener("mousewheel" , function( evt ){
  // If the mouse does not move into the magnifying glass, the wheel event function will not be executed if(!this.magnifier_start){ return false }
  var e = evt || event;
  // Determine whether the scroll wheel is up (zoom out) or down (zoom in);
  this.changeCutBoxScale( e.wheelDelta > 0 ? "narrow" : "large" );
 }.bind(this));
}

Element display and hide functions:

Magnifier.prototype.eleToggle = function( type ) {
 // According to the type type, determine the display attribute value of the element: block | none
 this.cutting_box_ele.style.display = type === "show" ? "block" : "none";
 this.big_box_ele.style.display = type === "show" ? "block" : "none";
}

Process the x and y values ​​of the coordinate points obtained when the mouse moves:

Magnifier.prototype.factoryPosition = function( x , y ){
 // Calculate the left and top offsets of cutting_box based on the received x and y var _left = x - this.small_box_offset.left - this.cutting_box_offset.width / 2;
 var _top = y - this.small_box_offset.top - this.cutting_box_offset.height / 2
 // The maximum value of left and top of cutting_box var _left_max = this.small_box_offset.width - this.cutting_box_offset.width;
 var _top_max = this.small_box_offset.height - this.cutting_box_offset.height;
 //Minimum boundary monitoring;
 _left = _left <= 0 ? 0 : _left;
 _top = _top <= 0 ? 0 : _top
 // Maximum value detection _left = _left >= _left_max ? _left_max : _left;
 _top = _top >= _top_max ? _top_max : _top;
 // Return the processed coordinate point value and the ratio coefficient of the moving distance to the maximum value return {
  x : _left,
  y : _top,
  xp: _left / _left_max,
  yp:_top / _top_max
 }
}

Small picture moves, large picture zooms in and follows function:

Magnifier.prototype.eleMove = function( position_obj ) {
 // Left cutting_box moving range this.cutting_box_ele.style.left = position_obj.x + "px";
 this.cutting_box_ele.style.top = position_obj.y + "px";
 // The moving range of the big image big_img. The moving directions of cutting_box and big_img are opposite this.big_img_ele.style.left = -position_obj.xp * this.big_img_boundary.left_max + "px";
 this.big_img_ele.style.top = -position_obj.yp * this.big_img_boundary.top_max + "px";
}

Enlarge picture function:

Magnifier.prototype.scaleBigImg = function(){
 // Enlargement ratio;
 var width_p = this.big_box_offset.width / this.cutting_box_offset.width;
 var height_p = this.big_box_offset.height / this.cutting_box_offset.height;
 // Get the width and height of big_img after enlargement;
 this.big_img_offset = {
  width : width_p * this.small_box_offset.width,
  height : height_p * this.small_box_offset.height,
 }
 // Calculate the boundaries of big_img motion;
 this.big_img_boundary = {
  left_max : this.big_img_offset.width - this.big_box_offset.width,
  top_max : this.big_img_offset.height - this.big_box_offset.height
 }
 // Set proportional width and height for the image;
 this.big_img_ele.style.width = this.big_img_offset.width + "px";
 this.big_img_ele.style.height = this.big_img_offset.height + "px";
}

When the mouse wheel is scrolled, the size of the cutting_box on the left needs to be changed at the same time:

Magnifier.prototype.changeCutBoxScale = function( type ){
 switch ( type ) {
  // Enlarge case "large":
   this.cutting_box_offset.width += 2;
   this.cutting_box_offset.height += 2;
   // Move cutting_box to the left and up to keep the mouse in the center this.res.x --;
   this.res.y --; 
   break;
  // Narrow case "narrow":
   this.cutting_box_offset.width -= 2;
   this.cutting_box_offset.height -= 2;
   this.res.x++;
   this.res.y++;
   break;
  default:
   break;
 }
 this.cutting_box_ele.style.width = this.cutting_box_offset.width + "px";
 this.cutting_box_ele.style.height = this.cutting_box_offset.height + "px";
 // After the position changes, call the corresponding ratio calculation tool;
 this.scaleBigImg();
 // Recalculate the large image motion;
 this.eleMove(this.res);
}

Additional functions: Switch between multiple pictures and enlarge the corresponding pictures.
Add tags: data-src custom attributes to store different image paths

<button class="btn" data-src=""><img src="" alt=""></button>
<button class="btn" data-src=""><img src="" alt=""></button>

Finally, after instantiating the magnifying glass object, you only need to bind the click or move event to each button, and then replace the src attribute value of the img in the small and big containers with the corresponding data-src attribute value, as shown below:

// Select all buttons representing different pictures var btns = document.querySelectorAll(".btn");
// Select the img tags in the small and big containers var imgs = document.querySelectorAll(".big img,.small img");
for(var i = 0 ; i < btns.length ; i ++){
 btns[i].onclick = function(){
  // Get the different data-src attributes on each button var src = this.getAttribute("data-src");
  for(var k = 0 ; k < imgs.length ; k ++){
   // Replace the attribute value of the corresponding src attribute imgs[k].src = src;
  }
 }
}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Implementation process of the magnifying glass effect in the Javascript example project
  • JavaScript realizes magnifying glass special effects
  • JavaScript imitates Jingdong magnifying glass special effects
  • JavaScript imitates Jingdong magnifying glass effect
  • JavaScript imitates Taobao magnifying glass effect
  • JavaScript to achieve magnifying glass effect
  • Ideas and codes for realizing magnifying glass effect in js
  • JavaScript implementation of magnifying glass details

<<:  Summarize the common application problems of XHTML code

>>:  Detailed explanation of MYSQL large-scale write problem optimization

Recommend

Vue implements carousel animation

This article example shares the specific code of ...

Linux gzip command compression file implementation principle and code examples

gzip is a command often used in Linux systems to ...

React implements a general skeleton screen component example

Table of contents What is a skeleton screen? Demo...

How to view the network routing table in Ubuntu

What are Routing and Routing Table in Linux? The ...

JavaScript to show and hide the drop-down menu

This article shares the specific code for JavaScr...

100 ways to change the color of an image using CSS (worth collecting)

Preface “When it comes to image processing, we of...

Detailed explanation of how to use grep to obtain MySQL error log information

To facilitate the maintenance of MySQL, a script ...

Detailed tutorial on installing CUDA9.0 on Ubuntu16.04

Preface: This article is based on the experience ...

Implement a simple search engine based on MySQL

Table of contents Implementing a search engine ba...