Detailed description of JavaScript image enlargement

Source: Internet
Author: User


Run code box
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" ""> <br/> <HTML xmlns = ""> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> <title> magniier </title> <br/> <style type =" text/CSS "> <br/> # magniier {< br/> width: 342px; <br/> Height: 420px; <br/> position: absolute; <br/> top: 100px; <br/> left: 250px; <br/> font-size: 0; <br/> border: 1px solid #000; <br/>}< br/># IMG {<br/> width: 342px; <br/> Height: 420px; <br/>}< br/># browser {<br/> border: 1px solid #000; <br/> Z-index: 100; <br/> position: absolute; <br/> Background: #555; <br/>}< br/># mag {<br/> border: 1px solid #000; <br/> overflow: hidden; <br/> Z-index: 100; <br/>}< br/> </style> <br/> <SCRIPT type = "text/JavaScript"> <br/> function geteventobject (w3cevent) {// event standardization function <br/> return w3cevent | window. event; <br/>}< br/> function getpointerposition (e) {// browser-compatible mouse X, Y to obtain the function <br/> E = E | geteventobject (E); <br/> var x = E. pagex | (E. clientx + (document.doc umentelement. scrollleft | document. body. scrollleft); <br/> var y = E. pagey | (E. clienty + (document.doc umentelement. scrolltop | document. body. scrolltop); </P> <p> return {'X': X, 'y': Y };< br/>}< br/> function setopacity (ELEM, level) {// set transparent value for compatible browsers <br/> If (ELEM. filters) {<br/> ELEM. style. filter = 'Alpha (opacity = '+ level X 100 +') '; <br/>}else {<br/> ELEM. style. opacity = level; <br/>}< br/> function CSS (ELEM, Prop) {// css setting function, allowing you to easily set CSS values, and compatible with setting transparent values <br/> for (var I in prop) {<br/> if (I = 'opacity ') {<br/> setopacity (ELEM, prop [I]); <br/>}else {<br/> ELEM. style [I] = prop [I]; <br/>}< br/> return ELEM; <br/>}< br/> var magnifier = {<br/> M: NULL, </P> <p> init: function (Magni) {<br/> var M = This. M = Magni | {<br/> cont: NULL, // Div loaded with the original image <br/> IMG: NULL, // enlarged image <br/> MAG: null, // zoom in Box <br/> scale: 15 // proportional value. The larger the value is, the larger the value is. However, if Division is not allowed, some small white edges will be generated, and I do not know how to solve them now <br/>}</P> <p> CSS (M. IMG, {<br/> 'position': 'absolute ', <br/> 'width': (M. cont. clientwidth * m. scale) + 'px ', // The width * Ratio of the original image <br/> 'height': (M. cont. clientheight * m. scale) + 'px '// The height * Ratio of the original image <br/>}) </P> <p> CSS (M. mag, {<br/> 'display': 'none', <br/> 'width': M. cont. clientwidth + 'px ', // M. cont is the original image, equal to the original image width <br/> 'height': M. cont. clientheight + 'px ', <br/> 'position': 'absolute', <br/> 'left': M. cont. offsetleft + M. cont. offsetwidth + 10 + 'px ', // The Position of the enlarged box is 10px far from the right of the original image <br/> 'top': M. cont. offsettop + 'px '<br/>}) </P> <p> var borderwid = m. cont. getelementsbytagname ('div ') [0]. offsetwidth-M. cont. getelementsbytagname ('div ') [0]. clientwidth; // obtain the width of the border </P> <p> CSS (M. cont. getelementsbytagname ('div ') [0], {// M. cont. getelementsbytagname ('div ') [0] is the browser box <br/> 'display': 'none', // start to set to invisible <br/> 'width ': m. cont. clientwidth/m. scale-borderwid + 'px ', // width/proportion of the original image-Border width <br/> 'height': M. cont. clientheight/m. scale-borderwid + 'px ', // The height/proportion of the original image-Border width <br/> 'opacity': 0.5 // set the transparency <br/> }) </P> <p> M. IMG. src = m. cont. getelementsbytagname ('img ') [0]. SRC; // use the SRC value of the original image to enlarge the image <br/> M. cont. style. cursor = 'crosshair'; </P> <p> M. cont. onmouseover = magnifier. start; </P> <p >}, </P> <p> Start: function (e) {</P> <p> If (document. all) {// only run in IE, mainly to prevent the SELECT statement of IE6 from overwriting <br/> magniier. createiframe (magniier. m. IMG); <br/>}</P> <p> This. onmousemove = magnifier. move; // This points to M. cont <br/> This. onmouseout = magnifier. end; <br/>}, </P> <p> move: function (e) {<br/> var Pos = getpointerposition (E ); // event standardization </P> <p> This. getelementsbytagname ('div ') [0]. style. display = ''; </P> <p> CSS (this. getelementsbytagname ('div ') [0], {<br/> 'top': math. min (math. max (POS. y-this. offsettop-parseint (this. getelementsbytagname ('div ') [0]. style. height)/2, 0), this. clientheight-this. getelementsbytagname ('div ') [0]. offsetheight) + 'px ', <br/> 'left': math. min (math. max (POS. x-this. offsetleft-parseint (this. getelementsbytagname ('div ') [0]. style. width)/2, 0), this. clientwidth-this. getelementsbytagname ('div ') [0]. offsetwidth) + 'px '// left = mouse X-this. offsetleft-view box width/2, math. max and math. min makes the browser box not exceed the image <br/>}) </P> <p> magniier. m. mag. style. display = ''; </P> <p> CSS (magnifier. m. IMG, {<br/> 'top':-(parseint (this. getelementsbytagname ('div ') [0]. style. top) * magniier. m. scale) + 'px ', <br/> 'left':-(parseint (this. getelementsbytagname ('div ') [0]. style. left) * magniier. m. scale) + 'px '<br/>}) </P> <p >}, </P> <p> end: function (E) {<br/> This. getelementsbytagname ('div ') [0]. style. display = 'none'; <br/> magnifier. removeiframe (magnifier. m. IMG); // destroy IFRAME </P> <p> magniier. m. mag. style. display = 'none'; <br/>}, </P> <p> createiframe: function (ELEM) {<br/> var layer = document. createelement ('iframe'); <br/> layer. tabindex = '-1'; <br/> layer. src = 'javascript: false; '; <br/> ELEM. parentnode. appendchild (layer); </P> <p> layer. style. width = ELEM. offsetwidth + 'px '; <br/> layer. style. height = ELEM. offsetheight + 'px '; <br/>}, </P> <p> removeiframe: function (ELEM) {<br/> var layers = ELEM. parentnode. getelementsbytagname ('iframe'); <br/> while (layers. length> 0) {<br/> layers [0]. parentnode. removechild (layers [0]); <br/>}< br/> window. onload = function () {<br/> magniier. init ({<br/> cont: document. getelementbyid ('magniier '), <br/> IMG: document. getelementbyid ('magnikierimg '), <br/> MAG: document. getelementbyid ('mag'), <br/> scale: 3 <br/> }); <br/>}< br/> </SCRIPT> <br/> </pead> <br/> <body> <br/> <Div id = "magniier"> <br/> <br/> <Div id = "Browser"> </div> <br/> </ div> <br/> <Div id = "mag"> </div> <br/> <Select style = "position: absolute; top: 200px; left: pixel PX; width: 100px; "> <br/> <option> select test </option> <br/> <option> overwrite </option> <br/> </SELECT> <br/> </body> <br/> </ptml>
[Ctrl + A select all tips: you can modify some code and then press run]

I have previously written a jquery image to enlarge the image, but there are some minor problems. I have recently rewritten it and made some detailed improvements. most bugs are improved, and jquery is not used.

Program description

The main methods are as follows:

  • Init: Running Method
  • Start: process the event of moving the cursor into the div.
  • Move: The event processing when the mouse moves in the DIV
  • End: processing of events after Mouse Removal

Program Introduction

Main thinking: When the mouse moves into the image, the DIV of the zoom-in layer appears, and then changes the top and left values of the image in the zoom-in Layer Based on the mouse movement, the reality of keeping two places consistent. The ratio of the two images to the data is set, and the width and height values are used to enlarge the image. The following is a detailed explanation:

In the init method, the size of the DIV layer of the browser box, the size of the enlarged box, and the size of the enlarged image are mainly processed.
View the width and height of the DIV and obtain the size/proportion of the original image. For details, see the code:

CSS (M. Cont. getelementsbytagname ('div ') [0], {// M. Cont. getelementsbytagname ('div') [0] is the browser box
'Display': 'none', // start to set to invisible
'Width': M. Cont. clientwidth/M. Scale-borderwid + 'px', // width/proportion of the original image-Border Width
'Height': M. Cont. clientheight/M. Scale-borderwid + 'px', /// height/proportion of the original image-Border Width
'Opacity ': 0.5 // sets the transparency.

The size of the enlarged box is set to the same size as the original image. The Code is as follows:

CSS (M. Mag ,{
'Display': 'none ',
'Width': M. Cont. clientwidth + 'px ', // M. cont is the original image
'Height': M. Cont. clientheight + 'px ',
'Position': 'absolute ',
'Left': M. Cont. offsetleft + M. Cont. offsetwidth + 10 + 'px ', // The Position of the enlarged box is 10px far from the right of the original image.
'Top': M. Cont. offsettop + 'px'

The enlarged image size is the ratio of the original image size *. The Code is as follows:

CSS (M. IMG ,{
'Position': 'absolute ',
'Width': (M. Cont. clientwidth * M. Scale) + 'px', // width * Ratio of the original image
'Height': (M. Cont. clientheight * M. Scale) + 'px' // The height * Ratio of the original image

Because the scale-up is based on the scale-up, you need to carefully calculate the browsing box and the scaled-up image. This is one of the main ideas of this program.



In the program written for the first time, onmouseover is saved directly, because onmousemove can satisfy the function. Onmouseover is used this time to avoid the use of select, in IE6, select cannot set the Z-index value, so that the sudden appearance of the enlarged box cannot overwrite the select. The details are discussed below,

In the move method, the most important thing is that when you move the mouse, the browsing box moves with the mouse, and the enlarged image also moves ,, make the displayed range of the enlarged image consistent with the position of the original image in the browser box.

Let's talk about the browser box moving with the mouse. The main code is as follows:

Top: pos. Y-This. offsettop-parseint (this. getelementsbytagname ('div ') [0]. style. Height)/2
Left: pos. X-This. offsetleft-parseint (this. getelementsbytagname ('div ') [0]. style. width)/2

Because yes, events are bound to M. cont, this points to M. Cont.

From the image, we can see that left = mouse X-this. offsetleft-the browser box width/2, so the code can be obtained based on this geometric idea, and the top value is also obtained based on the same principle. I will not explain it in detail here. The following code changes the top and left values of the enlarged image while moving the mouse:

CSS (magnifier. M. IMG ,{
'Top':-(parseint (this. getelementsbytagname ('div ') [0]. style. Top) * magniier. M. Scale) + 'px ',
'Left':-(parseint (this. getelementsbytagname ('div ') [0]. style. Left) * magniier. M. Scale) + 'px'

The Code clearly shows that you only need to set the * Ratio on the top and left values of the browser box. The reason for adding a negative number is that the default coordinate is (0, 0), while during the moving process, the start coordinate will only move in the negative direction.
There are two points to note in this method:


This. getelementsbytagname ('div ') [0]. style. Display = '';

It should be placed before setting top and left of this. getelementsbytagname ('div ') [0], because the width and height cannot be obtained if the display is none. If you put display = ''after setting top and left, a strange phenomenon may occur. You can try it. This problem has been bothering me for a long time, the problem was discovered only after multiple attempts. The strange phenomenon is as follows:


'Top': math. min (math. max (POS. y-this. offsettop-parseint (this. getelementsbytagname ('div ') [0]. style. height)/2, 0), this. clientheight-this. getelementsbytagname ('div ') [0]. offsetheight) + 'px ';

This long code may be confusing. I just use math. max () and math. min () avoids the use of the IF statement. I am a little lazy, just to make sure that the browser box does not go beyond the original image. Take a closer look at it.

The end method is clear, that is, to hide the browser box and the enlarged box.





[Overwrite select]

In order to overwrite select under IE6, I added two release methods createiframe and removeiframe. Create an iframe in the onmouseover event and destroy the IFRAME in onmouseout.

Createiframe: function (ELEM ){
VaR layer = Document. createelement ('iframe ');
Layer. tabindex = '-1 ';
Layer. src = 'javascript: false ;';
ELEM. parentnode. appendchild (layer );

Layer. style. width = ELEM. offsetwidth + 'px ';
Layer. style. Height = ELEM. offsetheight + 'px ';

First, use the negative tabindex value to exclude IFRAME from the tab sequence. Otherwise, the user may use the keyboard to navigate to it, which is messy, therefore, you must set the tabindex value to negative. In addition, you must set SRC to avoid issues on the SSL page. in IE, IFRAME without SRC is automatically loaded with about: blank. Ie regards this as an insecure page and generates a warning dialog box containing "Security and non-security content ". To avoid this problem, set SRC to "javascript: false ;". (This section is taken from <JavaScript essence>)
To avoid the confusion caused by IFRAME on the page, destroy IFRAME in onmouseout instead of hiding it.

Instructions for use

Due to time issues, it is not encapsulated very well, mainly on CSS, it is best to set according to the settings I set, it feels a bit messy. I hope you can understand it, and it will not be too difficult to modify it. Because I have a built-in CSS () function, you only need to set it up. Example:

Magniier. INIT ({
Cont: Document. getelementbyid ('magniier '),
IMG: Document. getelementbyid ('magnifierimg '),
MAG: Document. getelementbyid ('mag '),
Scale: 3

Cont is the abbreviation of container, which refers to the DIV that loads the original image;
IMG is a magnified image;
MAG is short for magniier, which refers to the enlarged box;
Scale is a proportional value. The larger the value is, the larger the value is. However, if Division is not allowed, some small white edges are generated. Currently, I do not know how to solve this problem;
The browser box and original image are M. cont. getelementsbytagname ('img ') [0] and M. cont. getelementsbytagname ('div ') [0]. Therefore, we recommend that you put only one Div and IMG In the DIV that loads the image.

PS: I just added some comments to the source code. Some of them are missing. The following code will explain the confusion caused by this pointer ~ I hope you can see what is going on... the more you use this, the less you feel that it is not easy to use...> ~ After an afternoon, I got tired and had a rest.

Related Article

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: 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.