您的位置:首页 > Web前端 > JavaScript

js图片自适应宽高

2016-04-08 15:56 435 查看
<!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>

<title>原创</title>

<script type="text/javascript" src="jquery-2.1.4.min.js"></script>

<script language="javascript">

/*

if(typeof jQuery == 'undefined'){

    window.alert("没有jquery");

}else{
window.alert("jquery");

}

*/

</script>

<style type="text/css">

.content{
width: 400px;
height: 400px;
border:1px solid green;
overflow: hidden;

}

</style>

<script type="text/javascript">
jQuery.fn.LoadImage = function(obj) {
var w = $(obj).width(); 
//alert (w);
var h = $(obj).height(); 
return this.each(function() {
var img_w = $(this).width(); 
//alert(img_w);
var img_h = $(this).height(); 
//alert(img_h);
if ((img_h/img_w)<(h/w)) {

var newW = (h * img_w) / img_h;
var mleft = -(newW-w)/2
$(this).css({
"width": newW,
"height": h,
'margin-left':mleft
}); //设置缩放后的宽度和高度 
}else if ((img_h/img_w)>(h/w)) { 
var newH = (w * img_h) / img_w;
var mtop = -(newH-h)/2
$(this).css({
"width": w,
"height": newH,
"margin-top":mtop
}); //设置缩放后的宽度和高度 
}

});

}

</script>

</head>

<body>
<div class="content"><img src="1.jpg"/></div> 
<div class="content"><img src="2.jpg"/></div> 
<div class="content"><img src="3.jpg"/></div> 
<div class="content"><img src="4.jpg"/></div> 

<script type="text/javascript"> 

$(window).load(function(){ 

$('.content img').LoadImage('.content'); 

}); 

</script>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: