jenney.qiu

导航

js将图片按比例缩放显示IE6

将图片按比例缩放显示在IE6下会失效,原因是在image未加载的的时候去获取Image的高度和宽度是获取不到的,所以可以判断若浏览器是IE6的话就在图片加载以后获取图片的高度和宽度然后再将图片进行比例缩放。具体实现代码如下:

//图片按比例缩放 @ImgID图片控件的ID,@iwidth指定的最大宽度,@iheight指定的最大高度
function DrawImage(ImgID, iwidth, iheight) {
            var image = new Image();
            image.src = $("#"+ImgID).attr("src");
            if (window.ActiveXObject) {
                var ua = navigator.userAgent.toLowerCase();
                var ie = ua.match(/msie ([\d.]+)/)[1];
                //判断是IE6
                if (ie == 6.0) {
                    image.onreadystatechange = function() {
                        if (image.readyState == "complete") {
                            ShowImg(image, iwidth, iheight,ImgID);
                        }
                    }
                }
                else {
                    ShowImg(image, iwidth, iheight,ImgID);
                }
            }
        }
        function ShowImg(image, iwidth, iheight,ImgID) {
            var widths = image.width;
            var heights = image.height;
            var newHeight, newWidth;
            if (widths > 0 && heights > 0) {
                if (widths / heights >= iwidth / iheight) {
                    if (widths > iwidth) {
                        newWidth = iwidth;
                        newHeight = (heights * iwidth) / widths;
                    } else {
                        newWidth = iwidth;
                        newHeight = (heights * iwidth) / widths;
                    }
                }
                else {
                    if (heights > iheight) {
                        newHeight = iheight;
                        newWidth = (widths * iheight) / heights;
                    } else {
                        newHeight = iheight;
                        newWidth = (widths * iheight) / heights;
                    }
                }
            }
            $("#"+ImgID).css("height", newHeight);
            $("#"+ImgID).css("width", newWidth);
       //以下三行代码是将图片设置在其外的div的水平居中和垂直居中显示,此处DIV的宽度和高度均为325px
var newWidth = parseInt($("#"+ImgID).css("width")); var lefts = parseInt((325 - newWidth) / 2), tops = parseInt((325 - newHeight) / 2); $("#"+ImgID).css("margin-left", lefts + "px").css("margin-top", tops + "px"); }

这样在各种IE下都没有问题了。 

PS:我的淘宝店铺新开业,经营各种桌游,棋牌,希望大伙儿能来看看!http://201314yes.taobao.com/

posted on 2012-05-16 14:39  jenney.qiu  阅读(1449)  评论(0编辑  收藏  举报