One of the JavaScript learning notes: jQuery writing image proportional scaling and pre-loading
In the past, when JavaScript was always used, I wrote several functions on the page. Basically, I didn't consider function encapsulation and reuse. Recently, a project may have high requirements for this, therefore, we have studied jQuery-like encapsulation.
Here we will try to write similar JavaScript code in image proportional scaling and pre-loading.
Image proportional scaling and pre-loading are as follows (the pre-loading effect is sometimes not obvious ):
The main JavaScript code is as follows:
Copy codeThe Code is as follows:
(Function (){
Var yQuery = (function (){
Var yQuery = function (){
Return yQuery. fn. init ();
};
YQuery. fn = yQuery. prototype = {
Init: function (){
Return this;
},
// Image proportional scaling and pre-loading method declaration, but it feels awkward to write (return new imgResizeBox (e)
ImgResize: function (e ){
Return new imgResizeBox (e );
}
};
// Image Processing
Var imgResizeBox = function (e ){
// Image Parameters
Setting = {
ImgId: "", // the ID of the image container, such as. viewArea img
Height: 0,
Width: 0,
Loading: "images/lightbox-ico-loading.gif"
};
$. Extend (setting, e, setting); // Replace the Parameter
Var images = $ (setting. imgId); // obtain all images
$ (Images). hide (); // hide
Var loading = new Image (); // pre-load the Image
Loading. className = "loading ";
Loading. src = setting. loading;
$ (Images). after (loading );
// Pre-load function
Var perLoading = function ($ this ){
Var img = new Image ();
Img. src = $ this. src;
If (img. complete ){
ComputeImg. call ($ this );
Return;
};
Img. onload = function (){
ComputeImg. call ($ this );
Img. onload = function (){};
};
};
// Image scaling and image display functions
Var computeImg = function (){
Var m = this. height-setting. height;
Var n = this. width-setting. width;
If (m> n)
This. height = this. height> setting. height? Setting. height: this. height;
Else
This. width = this. width> setting. width? Setting. width: this. width;
$ (This). next (". loading"). remove ();
$ (This). show ();
};
// Call the preload function cyclically
Return $ (images). each (function (){
PerLoading (this );
});
}
Return yQuery;
})();
Window. yQuery = window. $ = yQuery ();
})();
The call code is as follows:
Copy codeThe Code is as follows:
$ (Document). ready (function ()
{
$. ImgResize ({imgId: ". viewArea img", height: 160, width: 270, loading: "http://www.jb51.net/images/2012/155618/2012062710243954.gif "});
});
The following is a simple source code: jsDemo_jb51.rar.