2016-11-24 71 views
-1

我使用'.getComputedStyle'在浏览器窗口中间垂直对齐对象。该函数在页面加载时和'window.resize'时被调用。仅在window.resize上激活JS函数

问题是只有在调整浏览器窗口大小时才起作用,从一开始就不起作用。我多次使用这种方法,这是我第一次遇到这个问题。

在此先感谢!

这里是我的codepen和JS代码:

http://codepen.io/SamuelVDP/pen/JbNZgM

function controlHeight() { 
    var resCarousel; 

    for (var i = 0; i < carouselCell.length; i++) { 
    var carouselControl = window.getComputedStyle(carouselCell[i]); 
    var carouselWidth = carouselControl.width; 

    if (carouselWidth.length === 5) { 
     resCarousel = carouselWidth.substr(0, 3); 
    } else if (carouselWidth.length === 6) { 
     resCarousel = carouselWidth.substr(0, 4); 
    } else if (carouselWidth.length === 9) { 
     resCarousel = carouselWidth.substr(0, 7); 
    } else if (carouselWidth.length === 10) { 
     resCarousel = carouselWidth.substr(0, 8); 
    } 

    carouselCell[i].style.height = (resCarousel * 0.57) + 'px'; 
    carouselCell[i].style.marginTop = ((window.innerHeight - (resCarousel * 0.57))/2) + 'px'; 

    var p = document.getElementsByTagName('p')[0]; 
    var pControl = window.getComputedStyle(p); 
    var pHeight = pControl.height; 
    var resP = pHeight.substr(0, 2); 

    p.style.marginTop = ((window.innerHeight - resP)/2) + 'px'; 

    console.log(carouselCell[i].style.marginTop); 
    } 
} 
+0

函数在主函数中被调用。这个函数在页面加载时被调用,所以它不应该有任何区别。 – SamuelVDP

回答

0

打电话给你的窗口功能调整事件。

$(window).resize(function(){ controlHeight(); });  
+0

我已经这样做了。问题是页面加载时不起作用,只有在调整窗口大小时才起作用。 – SamuelVDP