首页 > 代码库 > 写个js动态调整图片宽高 (原创)

写个js动态调整图片宽高 (原创)

<body style="TEXT-ALIGN: center;">
<div id="testID" style="background:red;MARGIN-RIGHT: auto; MARGIN-LEFT: auto; width:173;height:184">
        <img src="http://e.hiphotos.baidu.com/image/pic/item/024f78f0f736afc385a0f0e7b119ebc4b6451280.jpg" style="display:none;">
</div>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script >
    var selector = $("#testID").find("img"); //选择器
    selector.hide();
    var containerWidth = 173 * 1; //173:容器宽度 1:宽度填充百分之百
    var containerHeight = 184 * 0.9; //184:容器高度 0.9:高度填充百分之九十


    
    //等所有图片都加载完毕再动态计算图片宽高进行调整
    window.onload=DynamicSetImageWithHeight;
    
    //动态调整宽高函数
     function DynamicSetImageWithHeight() {
        selector.each(function () {
            var width = $(this).width();
            var height = $(this).height();
            if (width > containerWidth) {
                height = height * containerWidth / width;
                width = containerWidth;
            }

            if (height > containerHeight) {
                width = width * containerHeight / height;
                height = containerHeight;
            }
            width = parseInt(width);
            height = parseInt(height);
            $(this).css({ width: width.toString() + "px", height: height.toString() + "px" });
        });
        selector.fadeIn();
    };
</script>