<!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>ul li图片文字混排不加overflow:hidden,使文字垂直居中(完美版)</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<link type="text/css" rel="Stylesheet" href="css/a_common.css" />
<style type="text/css">
#k_img_ul{ float:left; width:1000px; padding:18px 0 0 0; }/*通过这个ul来控制这个部分与外部的距离*/
#k_img_ul li{ float:left; width:124px; text-align:center; border:1px solid red;}
#k_img_ul li span{ display:block; width:120px; height:50px; padding:2px; border:1px solid #ccc; }/*这部分的CSS与js要对应* /
#k_img_ul li span a{ display:block; width:120px; height:50px; }
#k_img_ul p{ height:24px; line-height:24px;}
/*#k_img_ul img { background: #FFF; width: expression(this.width > 100 && this.height < this.width ? 100 : true); height: expression(this.height > 100 ? 100 : true); margin-top:expression(Math.ceil((100-this.height)/2));max-width: 100px; max-height: 100px; }*/ /*firefox不兼容--||恢常遗憾*/
</style>
</head>
<body>
<ul id="k_img_ul">
<li><span><a href="#"><img src="5.jpg" /></a></span><p>king</p></li>
<li><span><a href="#"><img src="1.jpg"/></a></span><p>king</p></li>
<li><span><a href="#"><img src="6.jpg" /></a></span><p>king</p></li>
<li><span><a href="#"><img src="7.jpg" /></a></span><p>king</p></li>
<li><span><a href="#"><img src="8.jpg" /></a></span><p>king</p></li>
<br class="clear" />
</ul>
<script type="text/javascript">
function makeMid(className,width,height){
var h=className.height();//图片原本的高度
var w=className.width();//图片原本的宽度
var v_h=(width*h)/w;//调整后的高度
var v_w=(height*w)/h;//调整后的宽度
var compare=width/height;//宽和高的比值
var compare_now=w/h;
var marginT_all=Math.abs(Math.round(height/2-h/2));//当图片的高小于定高时
var marginT_all=marginT_all+"px 0 0 0";
if(compare_now>compare)//从比例上更宽了
{
var marginT=Math.abs(Math.round(height/2-v_h/2));
marginT=marginT+"px 0 0 0";
if((w>width)||(w==width))//宽大于等定值时
{
className.css({width:width,height:v_h,margin:marginT});
}
else
{
className.css({width:w,height:h,margin:marginT_all});
}
}
if(compare>compare_now)//从比例上更高了
{
var marginT1=Math.abs(Math.round(width/2-v_w/2));
marginT1="0 "+marginT+"px 0 0";
if((h>height)||(h==height))//高大于定值
{
className.css({width:v_w,height:height,margin:marginT1});
}
else
{
className.css({width:w,height:h,margin:marginT_all});
}
}
if(compare==compare_now)//宽高比例正好时
{
if((h>height)||(h==height))
{
className.css({ width:width,height:height});
}
else
{
marginT3=marginT3+"px 0 0 0";
className.css({ width:w,height:h,margin:marginT_all});
}
}
}
window.οnlοad=function(){
$("#k_img_ul>li>span>a>img").each(function(){
makeMid($(this),Number(120),Number(50));//参数值(要居中的图片元素,指定宽度,指定高度)
});
}
//});
</script>
</body>
</html>