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>
Javascript+Css 解决图片自适应
最新推荐文章于 2024-06-03 15:20:00 发布
针对页面上图片经常不能以原始比例缩放显示出来,导致部分图片看起来失真了!