读书人

如何用javascript来控制一个表格始终在

发布时间: 2014-01-12 00:03:16 作者: rapoo

怎么用javascript来控制一个表格始终在屏幕中间
无论是怎么滚动屏幕 表格始终在屏幕的正中央
用原生的javascript代码来写 而不是用其他的js库
怎么实现呢?

求大牛们给个例子。
[解决办法]
可以用CSS来实现。比如你的表格区域宽度800,高度500的话。


.always-center{
position:fixed;
width:800px;
height:500px;
z-index:99;
top:50%;
left:50%;
margin-left:-400px;
margin-top:-250px;
}
<div class="always-center">
<!-- table here -->
</div>

这个div放到</body>的前面,然后把你的table代码写到这个层里,就一直居中了。
[解决办法]
上面这回贴有人能删了不?

你可以区分浏览器,IE6中position:fixed是不起作用的,你必须在onresize事件中动态的将table设置为position:absolute,然后设置其left=(页面宽 table的宽) /2;top=(页面高 table的高)/ 2;计算中因为需要用到table的实际宽和高,所以你也必须先填充好了table的内容以后才行
[解决办法]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
<style type="text/css">
body{height:3000px;}
#test{width:500px;height:300px;border:1px solid red; position:fixed;margin:auto;top:0; left:0;bottom:0;right:0;}
</style>
<!--[if lte IE 6]>
<style>
#test{width:auto;height:auto;border:1px solid red; position:absolute;}
</style>
<script type="text/javascript">
function makeFixed(){
var _div = document.getElementById('test'),//获取待操作对象,table可放在里面
_clientWidth = (document.documentElement
[解决办法]
document.body).clientWidth,//获取当前可见区域宽度
_clientHeight = (document.documentElement
[解决办法]
document.body).clientHeight,//获取当前可见区域高度
//获取距顶部偏移量:可见区域距离最顶部+(当前可见区域高度-table高)/2:并保证当table高度超出后,使table头显示在最上
_top = (document.documentElement
[解决办法]
document.body).scrollTop + (_div.offsetHeight>_clientHeight ? 0 : (_clientHeight-_div.offsetHeight)/2);
_div.style.left = (_clientWidth-_div.offsetWidth)/2 +'px';
_div.style.top = _top + 'px';
};
window.onload = makeFixed;
window.onresize = makeFixed;
window.onscroll = makeFixed;
</script>
<![endif]-->
</head>
<body>
<div id="test"><table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table></div>
</body>
</html>


如果你的层可以固定高度和宽度,上面的代码不需要修改即可运行
如果你的层不允许固定高度和宽度,则将第一个#test{width:500px;height:300px;border:1px solid red; position:fixed;margin:auto;top:0; left:0;bottom:0;right:0;}定义删除,将<!--[if lte IE 6]>和<![endif]-->删除

读书人网 >JavaScript

热点推荐