Posted By

kayue on 12/31/10


Tagged


Versions (?)

Get window size and position


 / Published in: JavaScript
 

  1. var $ = function(id) {
  2. return document.getElementById(id);
  3. },
  4.  
  5. // 触点
  6. html = document.documentElement,
  7. box = $('cnt'),
  8. posX = $('left'),
  9. posY = $('top'),
  10. width = $('width'),
  11. height = $('height'),
  12.  
  13. // 浮动框大小
  14. boxWidth = box.offsetWidth,
  15. boxHeight = box.offsetHeight,
  16.  
  17. // 设置位置
  18. setPos = function() {
  19.  
  20. // 可视窗口
  21. var htmlWidth = html.clientWidth,
  22. htmlHeight = html.clientHeight,
  23.  
  24. // margin 值
  25. marginX = htmlWidth > boxWidth ? -(boxWidth/2) : 0,
  26. marginY = htmlHeight > boxHeight ? -(boxHeight/2) : 0,
  27.  
  28. // 可视宽度如果太小,要注意让内容能完整显示出来
  29. left = marginX == 0 ? 0 : '50%',
  30. top = marginY == 0 ? 0 : '50%';
  31.  
  32. box.style.left = left;
  33. box.style.top = top;
  34. box.style.marginLeft = marginX + 'px';
  35. box.style.marginTop = marginY + 'px';
  36. },
  37.  
  38. // 找到位置
  39. getPos = function() {
  40. var curLeft =0, curTop = 0, obj = box;
  41. if (obj.offsetParent) {
  42. while (obj.offsetParent) {
  43. curLeft += box.offsetLeft;
  44. curTop += box.offsetTop;
  45. obj = obj.offsetParent;
  46. }
  47. }
  48. posX.innerHTML = curLeft;
  49. posY.innerHTML = curTop;
  50. };
  51.  
  52. width.innerHTML = boxWidth;
  53. height.innerHTML = boxHeight;
  54.  
  55. setPos();
  56. getPos();
  57.  
  58. // 用户放大/缩小窗口,浮动应做相应处理
  59. window.onresize = function(){
  60. setPos();
  61. getPos();
  62. }

Report this snippet  

You need to login to post a comment.