JavaScript image amplification effect and Code Description

Source: Internet
Author: User

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ptml xmlns = "http://www.w3.org/1999/xhtml"> <pead> <meta http-equiv =" content-Type "content =" text/html; charset = UTF-8 "/> <title> Magnifier </title> <style type =" text/css "> # magnifier {width: 342px; height: 420px; position: absolute; top: 100px; left: 250px; font-size: 0; border: 1px solid #000 ;}# img {width: 342px; height: 420px ;}# Browser {border: 1px solid #000; z-index: 100; position: absolute; background: #555 ;}# mag {border: 1px solid #000; overflow: hidden; z-index: 100 ;}</style> </pead> <body> <select style = "position: absolute; top: 200px; left: pixel PX; width: 100px; "> <option> select test </option> <option> overwrite </option> </select> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
[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:

Copy codeThe Code is as follows:
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:
Copy codeThe 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:

Copy codeThe 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, it is necessary 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:

Copy codeThe 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, the event is bound to m. cont, so 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:

Copy codeThe Code is as follows:
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 is clear and can be obtained. 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:
1.
Copy codeThe Code is as follows:
This. getElementsByTagName ('div ') [0]. style. display = '';


Set this. before the top and left of getElementsByTagName ('div ') [0], the reason is that if the display is none, its width and height cannot be obtained. 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 phenomenon is as follows:

2.
Copy codeThe Code 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. ^
The end method is clear, that is, to hide the browser box and the enlarged box.
[Overwrite select]
In order to overwrite select in IE6, I added two release methods createIframe and removeIframe. They created an iframe IN THE onmouseover event and destroyed iframe in onmouseout.
Copy codeThe Code is as follows:
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 value of tabIndex 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, you can 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]
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 everyone 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 slightly. example:
Copy codeThe Code is as follows:
Magniier. init ({
Cont: document. getElementById ('magniier '),
Img: document. getElementById ('magnifierimg '),
Mag: document. getElementById ('mag '),
Scale: 3
});

Cont stands for container and refers to the div that loads the original image.
Img is a magnified image.
Mag stands for magniier. It 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 will be 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, it is recommended to put only one div and img In the div that loads the image.
[Program code]
Copy codeThe Code is as follows:
Function getEventObject (W3CEvent) {// event standardization function
Return W3CEvent | window. event;
}


Function getPointerPosition (e) {// compatible with the browser's mouse x, y to obtain the function
E = e | getEventObject (e );
Var x = e. pageX | (e. clientX + (document.doc umentElement. scrollLeft | document. body. scrollLeft ));
Var y = e. pageY | (e. clientY + (document.doc umentElement. scrollTop | document. body. scrollTop ));

Return {'X': x, 'y': y };
}

Function setOpacity (elem, level) {// sets transparent values for compatible browsers
If (elem. filters ){
Elem. style. filter = 'Alpha (opacity = '+ level * 100 + ')';
} Else {
Elem. style. opacity = level;
}
}

Function css (elem, prop) {// css setting function, which allows you to easily set css values and set transparent values.
For (var I in prop ){
If (I = 'opacity '){
SetOpacity (elem, prop [I]);
} Else {
Elem. style [I] = prop [I];
}
}
Return elem;
}

Var magnifier = {
M: null,

Init: function (magni ){
Var m = this. m = magni | {
Cont: null, // The div that loads the original image
Img: null, // enlarged image
Mag: null, // enlarge the box
Scale: 15 // proportional value. The larger the value is, the larger the value is. But the problem here is that if Division cannot be completed, some small white edges will be generated. Currently, I don't know how to solve this problem.
}

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
})

Css (m. mag ,{
'Display': 'none ',
'Width': m. cont. clientWidth + 'px ', // m. cont is the original image, equal to the original image width.
'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'
})

Var borderWid = m. cont. getElementsByTagName ('div ') [0]. offsetWidth-m. cont. getElementsByTagName ('div ') [0]. clientWidth; // obtain the border width.

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 of the original image/proportional value-border Width
'Opacity ': 0.5 // sets the transparency.
})

M. img. src = m. cont. getElementsByTagName ('img ') [0]. src; // use the src value of the original image to enlarge the image.
M. cont. style. cursor = 'crosshair ';

M. cont. onmouseover = magnifier. start;

},

Start: function (e ){

If (document. all) {// only execute in IE, mainly to prevent the select of IE6 from overwriting
Magniier. createIframe (magniier. m. img );
}

This. onmousemove = magnifier. move; // this points to m. cont
This. onmouseout = magnifier. end;
},

Move: function (e ){
Var pos = getPointerPosition (e); // event Standardization

This. getElementsByTagName ('div ') [0]. style. display = '';

Css (this. getElementsByTagName ('div ') [0], {
'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 ',
'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
})

Magniier. m. mag. style. display = '';

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'
})

},

End: function (e ){
This. getElementsByTagName ('div ') [0]. style. display = 'none ';
Magniier. removeIframe (magniier. m. img); // destroy iframe

Magniier. m. mag. style. display = 'none ';
},

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 ';
},

RemoveIframe: function (elem ){
Var layers = elem. parentNode. getElementsByTagName ('iframe ');
While (layers. length> 0 ){
Layers [0]. parentNode. removeChild (layers [0]);
}
}
}

Package and download files

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