2010-09-08 32 views
1

我有这个非常有用的一小段JavaScript中心mig div。我想使它适用于同一网站上的3个div,而不必重复3次相同的代码。使javascript-snippet影响3 div而不是1

关于如何做到这一点的任何想法? 把所有3个div放入1个div来照顾它,不是和可选项。

<script type="text/javascript"> 
    <!-- 
    function getWindowHeight() { 
     var windowHeight = 0; 
     if (typeof(window.innerHeight) == 'number') { 
      windowHeight = window.innerHeight; 
     } 
     else { 
      if (document.documentElement && document.documentElement.clientHeight) { 
       windowHeight = document.documentElement.clientHeight; 
      } 
      else { 
       if (document.body && document.body.clientHeight) { 
        windowHeight = document.body.clientHeight; 
       } 
      } 
     } 
     return windowHeight; 
    } 
    function setContent() { 
     if (document.getElementById) { 
      var windowHeight = getWindowHeight(); 
      if (windowHeight > 0) { 


      var contentElement = document.getElementById('outer'); 
       var contentHeight = contentElement.offsetHeight; 

       if (windowHeight < 570) { 
        contentElement.style.position = 'relative'; 
        contentElement.style.top = '30px'; 
       } 
       else if (windowHeight - contentHeight > 0) { 
        contentElement.style.position = 'relative'; 
        contentElement.style.top = ((windowHeight/2) - (contentHeight/2)) + 'px'; 
       } 





       else { 
        contentElement.style.position = 'static'; 
       } 

      } 
     } 
    } 
    window.onload = function() { 
     setContent(); 
    } 
    window.onresize = function() { 
     setContent(); 
    } 
    //--> 
    </script> 

问候特勒尔斯

回答

0

你并不需要检查是否存在document.getElementById。自罗马帝国以来它一直受到支持。

将id或必须居中的实际元素传递给您的函数。这消除了您的情况下对固定元素(#outer)的依赖关系,并使其更加灵活。另外尝试命名你的函数来表示他们实际在做什么。 setContent是一个非常通用的名称,并不表示任何地方的居中方面。

function centerElementWithId(id) { 
    .. 
    var contentElement = document.getElementById(id); 
    .. 
} 

然后三次调用它,

centerElementWithId('outer') 
centerElementWithId('secondDiv') 
centerElementWithId('thirdDiv'); 
+0

美丽!谢谢! – Troels 2010-09-08 17:09:25