元素.offsetWidth
返回元素的宽度,包含边框的
元素.clientWidth
返回元素的宽度,不包含边框的
元素.clientHeight和宽度语法相同
可视区的宽高
宽:document.documentElement.clientWidth
高:document.documentElement.clientHeight
css控制样式实现
方案一
#box {width: 400px;height: 300px;background: #ccc;border: 10px solid #f00;position: absolute;/* 垂直水平居中*/left: 50%;top: 50%;margin-left: -210px;margin-top: -160px; }
方案二
#box {width: 400px;height: 300px;background: #ccc;border: 10px solid #f00;position: absolute;/* 垂直水平居中*/left: 0;top: 0;bottom: 0;right: 0;margin: auto; }
js使用可视区宽高知识点实现
window.onload = function{var box = document.getElementById("box");var l = (document.documentElement.clientWidth - box.offsetWidth) / 2;var t = (document.documentElement.clientHeight - box.offsetHeight) / 2;box.style.left = l + 'px';box.style.top = t + 'px';};
元素的left=(可视区宽度-元素的宽度)/2
元素的top=(可视区高度-元素的高度)/2