居中

来源:互联网 发布:乐视没有mac版怎么看4K 编辑:程序博客网 时间:2024/05/01 05:00
function center(obj){
var windowWidth = document.documentElement.clientWidth;   
var windowHeight = document.documentElement.clientHeight;   
var popupHeight = $(obj).height();   
var popupWidth = $(obj).width();    
$(obj).css({   
 "position": "absolute",   
 "top": (windowHeight-popupHeight)/2+$(document).scrollTop(),   
 "left": (windowWidth-popupWidth)/2   
});  

}


//滚动的时候自动居中

$(window).scroll(function(){

center(obj);

});


//窗口变化自动居中

$(window).resize(function(){

center(obj);

});

showDiv();
function showDiv(obj){
$(obj).show();
center(obj);
$(window).scroll(function(){
 center(obj);
});
$(window).resize(function(){
 center(obj);
}); 
}

//按回车提交
$(document).keydown(function(e){
  if(e.keyCode ==13){
  //要调用的方法
}
});














<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="jquery.js"></script>
  <style>
    .div1{width: 300px;height: 400px;background: red;}
  </style>
</head>
<body>
<div class="div1"><span>居中居中</span></div>
</body>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
  <script>
    $('.div1 span').css({ 
      position:'absolute', 
      left: ($(".div1").width() - $('span').outerWidth())/2, 
      top: ($(".div1").height() - $('span').outerHeight())/2 + $(document).scrollTop() 
    }); 
  </script>
</body>
</html>

0 0
原创粉丝点击