Javascript+Css 解决图片自适应

针对页面上图片经常不能以原始比例缩放显示出来,导致部分图片看起来失真了!

id为img_wrapper里面的图片可以按原比例缩放显示

style1和style2分别是用来遮住多余的图片部分的样式

ps:或许这个别人都发过了,但毕竟是自己写的啊 ^-^!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="all" />
<meta name="author" content="colinivy" />
<title> Colinivy's world</title>
<style type="text/css">
* {
   margin:0; padding:0; list-style:none;
}
body {
   text-align:center;
}
#img_wrapper {
       overflow:hidden;
        position:relative;
        margin:auto;
        margin-top:100px;
        padding-top:5px;
        padding-left:5px;
        width:495px;
        height:332px;
        border: 1px solid #333;
        text-align:left;
}
.style1 {
   position:absolute;
   left:0px;
   top:332px;
   width:500px;
   height:5px;
   background-color: #fff;
}
.style2 {
   position:absolute;
   top:0px;
   left:495px;
   width:5px;
   height:337px;
   background-color: #fff;
}
</style>
</head>
<body>
<div id="img_wrapper">
   <img src="http://hiphotos.baidu.com/colinivy/pic/item/dc54473404433547251f14f9.jpg" alt="" />
</div>
</body>
<script type="text/javascript">
<!--
$id=function(id) {
   return document.getElementById(id);
}
function clipImage(imgArea,value,w,h,style1,style2) { //参数:img所属id,图像比,定义图像宽度和高度,遮罩样式1,2
   var img_wrapper =$id(imgArea) ;
   var obj =$id(imgArea).getElementsByTagName("img") ;
   for (var i=0;i<obj.length;i++ ) {
    var imgW =obj[i].clientWidth ;
    var imgH =obj[i].clientHeight ;
    if ((imgW/imgH)<value){
     obj[i].width=w;
     var addShadow = document.createElement("div");
     addShadow.className=style1;
     img_wrapper.appendChild(addShadow) ;
    }
    else {
     obj[i].height=h;
     var addShadow = document.createElement("div");
     addShadow.className=style2;
     img_wrapper.appendChild(addShadow) ;
    }
   }
}
clipImage("img_wrapper",1.5,490,327,"style1","style2");
//-->
</script>
</html>

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值