5-22 4,029 views
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
//div盒子对象
var div = $('.box');
//初始化居中
go_center(div);
//浏览器有变动的时候居中
window.onresize = function(){
go_center(div);
}
function go_center(obj){
var clientW = $(window).width();//浏览器宽度
var clientH = $(window).height();//浏览器高度
var width = obj.width();//div对象的宽
var height = obj.height();//div对象的高
//设置对象的top、left值
obj.css({
left: (clientW-width)/2,
top: (clientH-height)/2,
});
}
//点击div以外的地方隐藏
$(document).click(function() {
div.hide();
});
//阻止事件冒泡
div.click(function(event) {
event.stopPropagation();
})
})
</script>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.box{
background: red;
height: 200px;
width: 200px;
position: absolute;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>