核心代碼:
$(function() { $(".dvcontent img").each(function() { var maxwidth = 520; if ($(this).width() > maxwidth) { var oldwidth = $(this).width(); var oldheight = $(this).height(); var newheight = maxwidth/oldwidth*oldheight; $(this).css({width:maxwidth+"px",height:newheight+"px",cursor:"pointer"}); $(this).attr("title","點擊查看原圖"); $(this).click(function(){window.open($(this).attr("src"))}); } }); });
如果上面的代碼不能執行,可以使用下面的代碼:
$(window).load(function() { $(".dvcontent img").each(function() { var maxwidth = 600; if ($(this).width() > maxwidth) { var oldwidth = $(this).width(); var oldheight = $(this).height(); var newheight = maxwidth/oldwidth*oldheight; $(this).css({width:maxwidth+"px",height:newheight+"px",cursor:"pointer"}); $(this).attr("title","點擊查看原圖"); $(this).click(function(){window.open($(this).attr("src"))}); } }); });
通過css還有一種方法兼容IE6能讓圖片在超過規定的寬度時自動按比例縮小,但該寫法不符合W3C標準。代碼如下:
.cate img{ max-width: 600px; height:auto; width:expression(this.width > 600 ? "600px" : this.width); }
所以在做到盡量兼容IE和其他瀏覽器以及符合W3C的標準下就通過js來控制圖片的寬度了,下面使用jquery控制圖片顯示時的最大寬度,主代碼如下:
$(window).load(function() { $(".cate img").each(function() { var maxwidth = 600; if ($(this).width() > maxwidth) { $(this).width(maxwidth); } });});
代碼很簡單,就是cate樣式下的所以img的最大寬度只能為600px。.each(function(){......}),each在這里是對指定的圖片集合對象逐一調用下面的方法。這種jquery方法在IE6及以上瀏覽器和chrome及Firefox上都能實現控制圖片顯示時的最大寬度。
新聞熱點
疑難解答