想要达到的目的:让div元素随着网页的任意改变都是居中的
先放上代码:
<!DOCTYPE html>
<html>
<head>
<title>垂直居中</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(window).on('load resize', function(){
$("div").css({
"margin-top":($(window).height() - $("div").height())/2
});
});
</script>
<style type="text/css">
div{
margin: auto;/*只能控制水平方向的居中*/
}
</style>
</head>
<body>
<div style="width: 200px;height: 200px;background-color: yellow;"></div>
</body>
</html>
on(‘load resize’,function(){});
on();是可以让这一条语句有多个事件触发,可以理解为绑定
resize 调整浏览器窗口时触发
load 加载指定元素时触发
这里在我最开始写的时候 $(window)这些都放在了 $(documen).ready(function(){});里面,load就失效了,resize还有效