zoukankan      html  css  js  c++  java
  • javascript自动适应图片大小

    博客来源 http://blog.csdn.net/eduxh/article/details/1906246

    //图片自适应大小
    //id为img控件的id
    //width与height为img父控件的宽高——即img的最大宽高
    //示例:<img id="dd" src="ee.jpg" onload="imgFit('dd',100,200)" />"
    function imgFit(id,width,height)
    {
        var imageArr=document.getElementById(id);
        if(imageArr.offsetWidth>width || imageArr.offsetHeight>height)
        {
            imageRate1=parseInt(imageArr.offsetWidth)/width;
            imageRate2=parseInt(imageArr.offsetHeight)/height;
            if(imageRate2>imageRate1)
                imageArr.style.height = imageArr.offsetHeight/imageRate2+"px";
            else
                imageArr.style.width = imageArr.offsetWidth/imageRate1 +"px";
        }
    }
    添加居中处理:

    function imgFit(imageArr,width,height)
    {
        //var imageArr=document.getElementById(id);
        //if(imageArr.offsetWidth>width || imageArr.offsetHeight>height)
        //{
        //alert(imageArr.style.marginTop);
            sWidth=imageArr.offsetWidth;
            sHeight=imageArr.offsetHeight;
            imageRate1=parseInt(imageArr.offsetWidth)/width;
            imageRate2=parseInt(imageArr.offsetHeight)/height;
            if(imageRate2>imageRate1)
            {
                imageArr.style.height = sHeight/imageRate2+"px";
                imageArr.style.marginLeft=(width-sWidth/imageRate2)/2+"px";
            }
            else
            {
                imageArr.style.width = sWidth/imageRate1 +"px";
                imageArr.style.marginTop=(height-sHeight/imageRate1)/2+"px";
            }   
            //alert(imageArr.offsetWidth+":"+imageArr.offsetHeight);
        //}
    }
  • 相关阅读:
    2011 年50+优秀的网页设计(下)
    25+令人惊讶的是令人难以置信的WordPress技术支持网站
    2011 漂亮的网站(上)
    2011 美丽的网站(下)
    38 jQuery和CSS多级下拉菜单解决方案(一)
    HTMl代码片段
    30 +漂亮的jQuery菜单导航(一)
    分享几套还算不错的后台模板(有源码下载)
    配 色 方 案
    一个小故事
  • 原文地址:https://www.cnblogs.com/Zoe-only/p/4598068.html
Copyright © 2011-2022 走看看