jQuery实现控制文章中图片大小

html格式

<code><ul id="picture">
    <li><img decoding="async" src="http://www.baidu.com/img/20130101_2b68ea564b3facde9b5fd867f9d474ba.gif"/></li>
    <li><img decoding="async" src="http://www.baidu.com/img/20130101_2b68ea564b3facde9b5fd867f9d474ba.gif"/></li>
  </ul></code>

jquery插件

<code>/*------------------------------------------------------------------------------
调用方式:$(selector).resizeImg({w:maxWidth,h:maxHeight});
--------------------------------------------------------------------------------
*/
(function($){
 $.fn.extend({
resizeImg:function(opt,callback){
var defaults={w:200,h:150};
var opts = $.extend(defaults, opt); 
  this.each(function(){
    $(this).load(function(){
    var imgWidth=this.width,imgHeight=this.height;
    if(imgWidth>opts["w"]){
  this.width=opts["w"];
  this.height=imgHeight*(opts["w"]/imgWidth);
  imgWidth=opts["w"];
  imgHeight=this.height;
  }
if(imgHeight>opts["h"]){
this.height=opts["h"];
this.width=imgWidth*(opts["h"]/imgHeight);
imgHeight=opts["h"];
imgWidth=this.width;
}   
//水平居中,垂直居中 
$(this).css({"margin-top":(opts["h"]-imgHeight)/2,"margin-left":(opts["w"]-imgWidth)/2}); 
}); 
});
}  
});
 })(jQuery);</code>

引用:

<code>$('#picture>li>img').resizeImg({w:150,h:150});</code>

0 thoughts on “jQuery实现控制文章中图片大小
添加一条新回复 回到顶部

亲爱的,主人已经关闭了这篇文章的评论 。