【jQuery插件】等比例缩放图片浏览-LoadImage

/ 七月 9th, 2010/ Posted in web技术文档 / No Comments / Views(1,053) »

做相册功能的时候经常会碰到这样一个问题,就是用户上传的照片尺寸,比例是很不固定的,如果是大图片经常会把页面撑开,即使你用了等比缩放。也要等图片加载完成,这是非常折磨人的。
这是一段网上找的代码,在Body标签中加入onload=”ReImgSize”进行调用:
view sourceprint?01 function ReImgSize() {

02 var await = document.getElementById(“Imgbox”); //定义要改变的图片的容器ID

03 var imgall = await.getElementsByTagName(“img”); //取得容器内所有的IMG标签

04 for (i = 0; i < imgall.length; i++) {

05 if (imgall[i].width > 500) //如果图片的宽度大于500

06 {

07 var oWidth = imgall[i].width; //取得图片的实际宽度

08 var oHeight = imgall[i].height; //取得图片的实际高度

09 imgall[i].width = “500″; //重设图片的宽度为500

10 imgall[i].height = oHeight * 500 / oWidth; //重设图片的高度

11 }

12 }

13}

但是这里仍有很多不人性的地方,碰到大图片的时候,加载是非常折磨人的事情。
(转载请注明出处:WEB前端开发 http://www.css88.com/)
这里找了一个jquery的LoadImage插件,自己做了少许的修改:
这个JQ插件的代码
view sourceprint?01/*

02///来源 http://wwww.css88.com

03///参数设置:

04scaling 是否等比例自动缩放

05width 图片最大高

06height 图片最大宽

07loadpic 加载中的图片路径

08*/

09(function($) {

10 jQuery.fn.LoadImage = function(settings) {

11 settings = jQuery.extend({

12 scaling: true,

13 width: 500,

14 height: 500,

15 loadpic: “”

16 },

17 settings);

18 return this.each(function() {

19 $.fn.LoadImage.Showimg($(this), settings);

20 });

21 };

22 $.fn.LoadImage.Showimg = function($this, settings) {

23 var src = $this.attr(“src”);

24 var img = new Image();

25 img.src = src;

26 var autoScaling = function() {

27 if (settings.scaling) {

28 if (img.width > 0 && img.height > 0) {

29 if (img.width / img.height >= settings.width / settings.height) {

30 if (img.width > settings.width) {

31 $this.width(settings.width);

32 $this.height((img.height * settings.width) / img.width);

33 }

34 else {

35 $this.width(img.width);

36 $this.height(img.height);

37 }

38 }

39 else {

40 if (img.height > settings.height) {

41 $this.height(settings.height);

42 $this.width((img.width * settings.height) / img.height);

43 }

44 else {

45 $this.width(img.width);

46 $this.height(img.height);

47 }

48 }

49 }

50 }

51 }

52 $this.attr(“src”, “”);

53 var loading = $(“\”图片加载中..\””);

54 $this.hide();

55 $this.after(loading);

56 $(img).load(function() {

57 autoScaling();

58 loading.remove();

59 $this.attr(“src”, this.src);

60 $this.show();

61

62 });

63 }

64})(jQuery);

这个是调用的方法:
view sourceprint?1$(function(){

2 $(“img”).LoadImage({scaling : true,

3 width : 500,

4 height : 200,

5 loadpic:”loading.gif”});

6});

查看demo:http://www.css88.com/demo/jQuery/LoadImage/demo.htm
(转载请注明出处:WEB前端开发 http://www.css88.com/)
另:其实如果没有IE6我们直接可以使用一个css属性就可以搞定这些复杂的工作,那就是max-width;
例如:img{max-width:500px;}
From – http://www.css88.com/archives/1228

anyShare分享到:
          

Related posts:

  1. WordPress永久链接格式对比及设置参考

Leave a Reply

Name required

Mail (will not be published) required

Website