Heim > Web-Frontend > js-Tutorial > Hauptteil

基于JQuery实现的图片自动进行缩放和裁剪处理_jquery

WBOY
Freigeben: 2016-05-16 17:01:46
Original
940 Leute haben es durchsucht

其实很早就想写一个这样的效果,至于原因?进来这个笔记,我相信你懂的。
一般门户网站,缺少不了大量的图片展示,而为了网站美观,图片又有各种不同尺寸,专业的网站编辑人员,会把图片处理成等比例的图片再上传,把网站弄得很好看,可惜,我想说,我遇到90%的网站编辑人员都是不专业的。
为了不让网站编辑人员毁掉我的心血,我决定做这样一个事情。

1、首先,在CSS里对图片定义好大小,如果JS不执行,就能看到拉伸的图片,也就是最正常的表现;
2、对每个定义图片大小的CSS多定义一个不常用的容器,这里我选用了斜体标签,并定义其CSS与同根img的CSS一模一样,并定义该容器里的img的CSS样式回归margin:0;padding:0;
我是这样做的:

复制代码 代码如下:

/*公用*/
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、定义图片处理函数,参考图片被定义的大小和原始大小,在保持比例的前提下填充满位置,再装进裁剪容器;
我的代码:

复制代码 代码如下:

//图片尺寸判断与处理,用裁剪容器包围 - By COoL
function cutImgz(obj){
    var image=new Image();
    image.src=obj.src;

    $this=$(obj);
    var iwidth=$this.width();//获取在CSS里固定的图片显示宽度
    var iheight=$this.height();//获取在CSS里固定的图片显示高度
    if(1*image.width*iheight!=1*iwidth*image.height){
        //原始图片的尺寸与CSS里固定的图片尺寸比例不一致,则进行处理
        if(image.width/image.height>=iwidth/iheight){
            $this.height(iheight+'px');
            $this.width((image.width*iheight)/image.height+'px');
        }
        else{
            $this.width(iwidth+'px');
            $this.height((image.height*iwidth)/image.width+'px');
        }

        //用cite装起来,做出裁剪效果
        $this.wrap('');
    }
}

4、在加载页面时遍历所有图片,判断其是否在缓存中,在缓存中则直接进行处理,不在缓存中则通过onload触发处理;
因为在缓存的图片秒load,在定义onload事件之前就已经load好,导致onload事件不被触发;而不在缓存的图片,若直接处理,图片未load出来,原始尺寸会被Image对象认为是空图,width和height都是0
我的代码:

复制代码 代码如下:

$('img').each(function(){
    var image=new Image();
    image.src=this.src;
    if(image.complete){
        //存在缓存中,立即处理
        cutImgz(this);
    } else{
        //不存在缓存中,onload处理
        this.onload=function(){
            cutImgz(this);
        }
    }
});
Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!