JQuery based on the realization of automatic image zooming and clipping processing

  • 2020-03-30 01:36:28
  • OfStack

Actually very early want to write an effect like this, as for the reason? Come in this note, I'm sure you understand.
General portal website, the lack of a lot of pictures show, and in order to website beautiful, pictures have a variety of different sizes, professional website editors, will be the image processing into the same proportion of the picture to upload, the site is very beautiful, unfortunately, I want to say, I encountered 90% of the website editors are not professional.
In order not to let the website editors destroy my efforts, I decided to do such a thing.

1. First, define the size of the image in CSS. If JS is not executed, you can see the stretched image, which is the most normal performance;
2. For each CSS that defines the size of the image, define one more container that is not commonly used. Cite> < / cite> , and define its CSS to be exactly the same as the CSS of the same root img, and define the CSS style regression margin of img in this container :0; Padding: 0;
Here's what I did:

cite{display:block;overflow:hidden;overflow:hidden !important;}

#BigPic img{display:block;padding:2px;width:240px;height:160px;border:1px solid #cccccc;}
#BigPic cite{display:block;padding:2px;width:240px;height:160px;border:1px solid #cccccc;}
#BigPic cite img{display:block;margin:0px;padding:0px;border:none;}

3. Define the picture processing function, refer to the size of the picture defined and the original size, and fill the position on the premise of maintaining the proportion, and then put it into the cutting container;
My code:

//Image size determination and processing, surrounded By a cropping container - By COoL
function cutImgz(obj){
    var image=new Image();

    var iwidth=$this.width();//Gets the image display width fixed in CSS
    var iheight=$this.height();//Gets the height of the image that is fixed in CSS
        //If the size of the original image is not in accordance with the fixed size ratio of the image in CSS, it is processed

        //Use cite to create a clipping effect
        $this.wrap('<cite />');

4. When the page is loaded, all the pictures are traversed to determine whether they are in the cache. If they are in the cache, they are processed directly.
(because the cached image second load is already loaded before the onload event is defined, the onload event is not triggered; If the Image is not cached, if the Image is not loaded, the original size will be considered as an empty Image by the Image object. The width and height are both 0.)
My code:

    var image=new Image();
        //Stored in the cache for immediate processing
    } else{
        //It's not in the cache. Onload handles it

Related articles: