通用垂直居中方法兼容各浏览器-改进
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了。
附:
实际使用中再发现什么问题我再来改。
感谢@吝啬你的温柔
之前的实现方法:
<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了。
附:
实际使用中再发现什么问题我再来改。
感谢@吝啬你的温柔
相关文章推荐
- 使层垂直居中的display:table-cell方法,多浏览器兼容
- div的内容图片垂直居中代码(兼容多浏览器)
- 兼容各种浏览器的图片垂直居中CSS解决方案
- 绝对定位的div的居中方法,下面的写法兼容IE系列浏览器和火狐浏览器。
- HTML标签内的连接、文本、垂直居中 兼容绝大部分浏览器
- 浏览器兼容CSS代码:按钮文字垂直居中(input button text vertical align)
- CSS完美兼容IE6/IE7/IE8/IE9/FF 通用方法 CSS对浏览器的兼容性具有很高的要求
- CSS中设置DIV垂直居中的N种方法 兼容IE浏览器
- 纯css实现DIV以及图片水平垂直居中兼容多种浏览器(实现过程)
- 浏览器兼容CSS代码:按钮文字垂直居中(input button text vertical align)
- 各浏览器下图片垂直居中的方法
- 让html元素随浏览器的大小自适应垂直居中的实现方法
- DIV水平垂直居中 兼容多种浏览器
- js获取浏览器滚动条垂直滚动距离scrollTop的兼容方法
- 未知高度定宽div水平居中及垂直居中(兼容ie6及其他牛逼浏览器)
- 纯js实现Div在页面垂直居中!可根据浏览器大小的改变而改变!兼容各种浏览器----神器版!
- div在页面垂直居中方法---增强改进版
- 兼容各种浏览器的图片垂直居中CSS解决方案
- [CSS]多浏览器兼容的垂直居中,兼容多个IE
- 浏览器兼容CSS代码:按钮文字垂直居中(input button text vertical align)