jquery Implementation Magnifier Effect instance code _jquery

Source: Internet
Author: User
Tags event listener html page first row

Before you do a detailed text description, first to share a simple jquery implementation Magnifier effect code, need a friend can take the code directly.

$ (function () {var mousex = 0;//mouse move position x var mousey = 0;//mouse move position y var maxleft = 0;//rightmost var maxtop = 0;//Bottom Var mark left = 0; Magnifier moves the left part of the distance var marktop = 0; Magnifier moves the top distance to var Perx = 0; Moved x percent of var pery = 0; Y percent moved var bigleft = 0; Large figure to move left distance var bigtop = 0; Large image to move top distance//change the position of the magnifying glass function Updatamark ($mark) {//By judging, let the small box only in the small map area to move if (markleft<0) {markleft = 0;} else if (markleft>maxleft) {markleft = Maxleft} if (marktop<0) {marktop = 0;}
else if (marktop>maxtop) {marktop = maxtop}//Gets the zoom ratio of the magnifying glass, that is, the proportion of this small box moving in the region Perx = markleft/$ (". Small"). Outerwidth ();
Pery = marktop/$ (". Small"). Outerheight ();
Bigleft =-perx*$ (". Big"). Outerwidth ();
Bigtop =-pery*$ (". Big"). Outerheight ();
Set the position of the small box $mark. css ({"Left": Markleft, "top": Marktop, "display": "Block"}); //Change the position function Updatabig () {$ (". Big") of the large image. css ({"Display": "Block", "left": Bigleft, "Top": Bigtop});}//Mouse out time function 
Cancle () {$ (". Big"). CSS ({"Display": "None"});
$ (". Mark"). CSS ({"Display": "None"}); ///////mouse small picture on mobile function imgMouseMove (event) {var $this = $ (this), var $mark = $ (this). Children (". Mark");//mouse in the position of the small map mousex = event.pagex-$this. Offset
(). left-$mark. Outerwidth ()/2;
Mousey = event.pagey-$this. Offset (). top-$mark. Outerheight ()/2;
Maximum Value Maxleft = $this. Width ()-$mark. Outerwidth ();
Maxtop = $this. Height ()-$mark. Outerheight ();
Markleft = MouseX;
Marktop = Mousey;
Updatamark ($mark);
Updatabig ();
$ (". Small"). Bind ("MouseMove", Imgmousemove). Bind ("MouseLeave", cancle);  })

You need to be aware that there are two main points in this

1. How to follow the position of "magnifying glass" and move the larger picture?

In fact, the use of a proportional relationship, when the "magnifying glass" to move how much proportion (is the proportion, not the specific value), the larger picture also use this ratio to multiply the large figure and the width and height, you can calculate the large figure should move how much distance;

2. Show the relationship between the area and Magnifier?

Here the "magnifying glass" should be larger than the size of the display area, which should be the larger picture and small proportional relationship. For example, the ratio of large and small figures is 1:2, the size of the "magnifying glass" area, and the size of the larger area should be 1:2, otherwise the "magnifying glass" covering the small plot area, and large image display area, the display of image information can not be consistent. (The example that is spoken in the wonderful class is not kept one to the other);

Well, the above code is relatively simple, the following for everyone through the text of the code to introduce the form of jquery to achieve Magnifier effect.

1.1.1 Summary

I believe we have seen or used the effect of magnifying glass, and even achieved the effect, it is generally used to enlarge the view of the product picture, some of the electrical business site (such as: Van, Jingdong Mall, Alibaba, etc.) have similar picture viewing effect.

In the next blog post, we will show you how to achieve Magnifier through jquery.

Directory

• Principle of realization

MouseMove Events

• Relative coordinates

Background-position Property

MouseWheel Events

1.1.2 Body

Implementation principle

First, let's explain how Magnifier works:

Method One: Prepare a large picture of high pixel, when the mouse is placed on the original image, loading shows the corresponding position of the larger picture.

Method Two: To enlarge the original picture, that is, adjust the length and width.

Above we introduced two ways to achieve magnifier effect, next, we will apply the above two ways to our jquery plug-in.

First, we need an IMG element to display the original object, as well as a container as a display box, and a large drawing object in the Display box. When the mouse moved to the original image, by the large map to the absolute positioning to show the corresponding position, to achieve a similar magnifying glass effect.

Next, let's define the Index.html page, which is specifically implemented as follows:

<!doctype html>
 
 

Above, we define the small object to display the original image, and the large object as a display box to display the corresponding position of the larger picture.

MouseMove Events

Next, we implement the magnifying glass effect through the jquery plug-in form, when the mouse moves over the small object, it will show the corresponding position of the large map in the large object, which involves the MouseMove event, so We need to implement the MouseMove event listener method (how to define the jquery plugin to refer to the custom jquery plugin step by step).

Now, let's implement the Jquery.imagezoom.js plugin!

; (function ($) {$.fn.imagezoom = function (options) {//the native width and height of the image. var native_width = 0, n
Ative_height = 0, current_width = 0, current_height = 0, $small = $ (". Small"), $large = $ (". large"); $ (". Magnify"). MouseMove (function (e) {/* ACT on the event */if (!native_width &&!native_height) {var image_obj
ECT = new Image ();
IMAGE_OBJECT.SRC = $small. attr (' src ');
Gets the image native height and width.
Native_height = Image_object.height;
Native_width = Image_object.width;
Gets the image current height and width.
Current_height = $small. Height ();
Current_width = $small. Width ();
else {//Gets. MAGINFY offset coordinates. var Magnify_offset = $ (this). Offset (),//Gets coordinates within. Maginfy.
mx = e.pagex-magnify_offset.left, my = e.pagey-magnify_offset.top;
Checks the mouse within. Maginfy or not. if (MX < $ (this). Width () && i < $ (this). Height () && mx > 0 && i > 0) {$large. fadeIn
(100); } ELSE {$large. fadeout;} if ($large. Is (": visible")) {/* Gets the large image coordinate by ratio Small.x/small.wid  th = large.x/large.width Small.y/small.height = Large.y/large.height Then we need to keep pointer in the centre
Deduct the half of large width and height.  * * var rx = math.round (mx/$small. Width () * native_width-$large. Width ()/2) *-1, ry = Math.Round (my/$small. Height () * native_height-$large. Height ()/2) *-1, BGP = rx + "px" + ry + "px", px = mx-$large. Width ()/2, py = my-$large
. Height ()/2;
$large. css ({left:px, top:py, BACKGROUNDPOSITION:BGP});
}
}
});  });

Above, I realized the MouseMove event listener method, when the mouse moved to the Magnify object, we need to get the current mouse relative coordinates position, below we explained through the picture how obtains the mouse the relative coordinate position.

Relative coordinates

Figure 1 Mouse relative coordinate position

When the mouse is moved to the Magnify object, we need to get the relative coordinates of the mouse in the magnify, where we define the relative coordinates (MX,MY), and by the above figure we know that the relative coordinates are equal to (Pagex-offsetleft, pagey-offsettop).

Now that we've got the coordinates of the mouse in the Magnify object, we need to get the corresponding coordinates for the larger graph, where we define the corresponding coordinates of the larger graph (rx,ry), and we can get the value of (rx,ry) by proportional relations.

Mx/small.width (width of the original) = Rx/native_width (width of the larger image)

My/small.height (length of the original) = Ry/native_height (Long of the larger image)

By the proportional relationship above, we know that the coordinates of the large graph (rx,ry) equals (Mx/small.width*native_width, my/small.height*native_height).

Through the above formula, we can get the corresponding coordinates of the large map, when the mouse moved to the Magnify object to show the corresponding position of the large map, then we need to implement a large image loading implementation.

Background-position Property

Before implementing the large picture loading display, first introduces the knowledge of the background positioning background-position in CSS.

Figure 2 CSS Background-position

Above, there is a picture of 100x100 pixel It consists of four colors, and each color is x50 pixels, next, we will modify the picture CSS Background-position property values to show the different locations of the picture.

We see that there are two lines of small squares under the big square, and they show different color positions, and here we do this by modifying the Background-position attribute values of each div element css.

For example: The first line of the Blue Square, we set the CSS Background-position property is: 0px-50px; this is the same as the original image to move up 50px, the first row of the other squares also through the left and right and up and down move to achieve.

But the second row of the square is even more strange, because they are composed of four colors, and the color of the position is different, this is how to achieve it?

For example: The first square of the second line, we set the CSS Background-position property to: 25px 25px; This is equivalent to the original image down and to the right to move 25px, because of the role of wrap it will fill the remaining position of color.

Now that we have learned the function of the CSS Background-position property, we can display the corresponding image part by modifying the Background-position property of the large object, which is implemented as follows:

$large. css ({
left:px,
top:py,
BACKGROUNDPOSITION:BGP

Above, we have the magnifying glass effect by loading the large graph, then we will introduce the magnifying glass effect by adjusting the length and width of the original image.

MouseWheel Events

In front, we enlarge the picture through the MouseMove event, here we will realize the picture amplification effect through the mouse wheel event.

Because, different browsers have different wheel events. There are three main types: OnMouseWheel (IE 6/7/8), MouseWheel (Ie9,chrome,safari and Opera) and Dommousescroll (only Firefox support), and the three events are not described here in detail.

Because of the differences between browsers, in order to achieve compatibility between browsers, we need to monitor the above three kinds of wheel events (Onmousewheel,mousewheel and Dommousescroll), specifically implemented as follows:

$ (". Magnify"). Bind (' Dommousescroll mousewheel onmousewheel ', function (e) {

Above, we have implemented compatible with different browser wheel event monitoring method, next, judge the wheel up or down also to consider the compatibility of different browsers, the mainstream browser (IE, Opera, Safari, Firefox, Chrome) in Firefox using detail, The remaining four classes use Wheeldelta, the two are only inconsistent on the value, the meaning is consistent, detail and Wheeldelta only two values, detail only take ±3,wheeldelta only ±120, where positive number is indicated as up, negative number indicates downward.

Since both detail and Wheeldelta have two values that indicate scrolling up or down, compatibility can be achieved in the following ways between different browsers, as follows:

$ (". Magnify"). Bind (' Dommousescroll mousewheel onmousewheel ', function (e) {

//cross-browser wheel Delta
var e = window.event | | E Old IE support.
var delta = Math.max ( -1, Math.min (1, (E.wheeldelta | |-e.detail)));

Above, we have handled the different browser wheel listener method, when the user needs to dynamically change the size of the original image when rolling the wheel, here we define the scaling ratio of scaling to 0.3, that is, every time the user rolls the original scroll of the wheel on the scale of 0.3, specifically implemented as follows:

Gets the image scaling height and width.
Native_height + + (native_height * scaling * delta);
Native_width + + (native_width * scaling * delta);
Update backgroud image size. 
$large. CSS (' background-size ', native_width + "px" + native_height + "px"); Now that we have achieved the effect of zooming the picture through the wheel, the complete implementation is as follows:/*********************************** * Author:jackson Huang * blog:http:// Www.cnblogs.com/rush * date:8/23/2013 * Reference: * http://www.sitepoint.com/html5-javascript-mouse-wheel/* http:// THECODEPLAYER.COM/WALKTHROUGH/MAGNIFYING-GLASS-FOR-IMAGES-USING-JQUERY-AND-CSS3 *******************************
****/
;  (function ($) {$.fn.imagezoom = function (options) {//the native width and height of the image. var defaults = {scaling:
0.3};
Combines object defaults and options. options = $.extend (defaults, options), Native_width = 0, native_height = 0, current_width = 0, current_height = 0, $small
= $ (". Small"), $large = $ (". large"); $ (". Magnify"). MouseMove (function (e) {/* ACT on the event */if (!native_width &&!native_height) {var image_object = new Image (); image_object.src = $small. attr (' src ');//Gets
The image native height and width.
Native_height = Image_object.height;
Native_width = Image_object.width;
Gets the image current height and width.
Current_height = $small. Height ();
Current_width = $small. Width ();
else {//Gets. MAGINFY offset coordinates. var Magnify_offset = $ (this). Offset (),//Gets coordinates within. Maginfy.
mx = e.pagex-magnify_offset.left, my = e.pagey-magnify_offset.top;
Checks the mouse within. Maginfy or not. if (MX < $ (this). Width () && i < $ (this). Height () && mx > 0 && i > 0) {$large. fadeIn
(100); else {$large. fadeout;} if ($large. Is (": visible")) {/* Gets the large image coordinate by ratio small.x/small. 
width = large.x/large.width Small.y/small.height = Large.y/large.height Then we need to keep pointer in the centre,
So deduct the half of. Large width and height.
*/var rx = Math.Round (mx/$small. Width () * native_width-$large. Width ()/2) *-1, ry = Math.Round (my/$small. Height () * native_height-$large. Height ()/2) *-1, BGP = rx + "px" + ry + "px", px = mx-$large. Width ()/2, py = my-$large. He
Ight ()/2;
$large. css ({left:px, top:py, BACKGROUNDPOSITION:BGP});
}
}
}); $ (". Magnify"). Bind (' Dommousescroll mousewheel onmousewheel ', function (e) {var image_object = new Image (); Image_
OBJECT.SRC = $large. attr (' src '); Cross-browser Wheel Delta e = window.event | | E
Old IE support.
var delta = Math.max ( -1, Math.min (1, (E.wheeldelta | |-e.detail)));
Gets the image scaling height and width.
Native_height + + (native_height * defaults.scaling * delta);
Native_width + + (native_width * defaults.scaling * delta);
The image can ' t smaller than the original. if (Native_height < current_height) {native_height = Current_height;} if (Native_width < current_width) {Native_w
Idth = Current_width; }//Console.log ("Native_height:" +Native_height + "Native_width:" + native_width);
Gets. Maginfy offset coordinates.
var Magnify_offset = $ (this). Offset (), mx = e.pagex-magnify_offset.left, my = e.pagey-magnify_offset.top;
Update backgroud image size.
$large. CSS (' background-size ', native_width + "px" + native_height + "px"); /* Gets The large image coordinate by ratio small.x/small.width = large.x/large.width Small.y/small.height = large.
Y/large.height then we need to keep pointer in the centre, so deduct the half of. Large width and height.  * * var rx = math.round (mx/$small. Width () * native_width-$large. Width ()/2) *-1, ry = Math.Round (my/$small. Height () * native_height-$large. Height ()/2) *-1, BGP = rx + "px" + ry + "px", px = mx-$large. Width ()/2, py = my-$large
. Height ()/2;
$large. css ({left:px, top:py, BACKGROUNDPOSITION:BGP});
});
};  }) (JQuery);

Figure 3 Magnifier Effect

Above, we achieved a magnifying glass effect, when we hover over the picture will automatically enlarge the corresponding parts of the picture, of course, we can adjust the magnification by the wheel.

1.1.3 Summary

In this blog, we introduced how to achieve Magnifier effect, in general, we can achieve Magnifier in two ways, and in the posting are given a detailed introduction, through the MouseMove event to load the effect of large graphics, MouseWheel events to achieve dynamic modification of the original image size.

This is just a simple program, we still have a lot of room for improvement, providing a rich and powerful program is our goal.

The above content to introduce jquery to realize the effect of magnifying glass, I hope to help you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.