您的位置:首页 > 其它

通用垂直居中方法兼容各浏览器-改进

2012-01-09 10:14 393 查看
之前写了一篇“拍脑门”得来的在各浏览器都能垂直居中的方法,要兼容各大浏览器,真的不得不借助脚本(JQuery已经使写脚本跟写CSS差不多了),大体思路就是取得要被居中元素的高度和其容器的高度,计算根据两个高度差计算出一个top来,随手写来,测试全部通过,不过事后一样,之前的脚本应该改良一下,不多说,直接给代码:

之前的实现方法:

<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
FixIt_Vertically("div1");
});
function FixIt_Vertically(id) {

var myheight = $("#" + id).outerHeight();
var myfatherheight = $("#" + id).parent().height();
var mytop = (myfatherheight - myheight) / 2;
$("#" + id).css("position", "relative").css("top", mytop + "px");
}
</script>改良后的代码:

<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
FixIt_Vertically("vertically");
});
function FixIt_Vertically(theclass) {
$("." + theclass).each(function () {
myheight = $(this).outerHeight();
myfatherheight = $(this).parent().height();
mytop = (myfatherheight - myheight) / 2;
$(this).css({ "position": "relative", "top": mytop });
});
}
</script>

看出来了吧?改进的地方就是把原来的id改成了class,这样,只要给每一个要垂直居中的元素加上一个vertically类(class="vertically"),就OK了。

附:

实际使用中再发现什么问题我再来改。

感谢@吝啬你的温柔
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: