2016-09-29 19 views
0

我在頁面上有兩個並排的元素。一個元素具有固定大小(100vh) - 。半角 - 另一個元素具有不同長度的文本 - .project-details。當流體文本容器延伸到比圖像容器更高時,我想對它應用一個類,以限制其子元素之一的高度,使文本容器的總高度回到與圖像高度相等的水平。jQuery outerHeight()&height改變窗口上的閃爍/失敗調整爲奇數像素

HTML:

 <div class="project-details left"> 
      <h1 class="project">Title</h1> 
      <div class="project-summary"> 
      <div class="summary-container"> 
       <p>A bunch of paragraphs here</p> 
      </div> 
      <a class="more" href="#">More</a> 
      <a class="less" href="#">Less</a> 
      </div> 
     </div> 
     <div class="hero hero-half right" style="background-image: url('/img/placeholder-vert1.jpg')"></div> 

相關的CSS:

.hero-half { 
    width: 50%; 
    height: 100vh; 
} 

.project-details { 
    width: 50%; 
    height: auto; 
} 

.project-summary .summary-container { 
    overflow: hidden; 

    &.restrict-height { 

    .summary-container { 
     // set max height 
     max-height: calc(100vh - 615px); 
    } 
    } 
} 

這裏是我的JS代碼:

$(function() { 

    var bpTab = 1024; 

    resize = function() { 
    var winWidth = $(window).width(); 
    var heroHeight = $(".hero-half").outerHeight(); 
    var boxHeight = $(".project-details").outerHeight(); 
    var $box = $(".project-summary"); 

    if (boxHeight > heroHeight && winWidth > bpTab) { 
     // if on desktop layout AND if text is pusing box too big, restrict box height 
     $box.addClass("restrict-height"); 
    } else { 
     // if not on desktop or text is not pushing box too big 
     $box.removeClass("restrict-height"); 
     $box.removeClass("is-expanded"); 
    }; 
    }; 

    // resize on window resize 
    $(window).bind("resize orientationchange", function(){ 
    resize(); 
    }); 

    // resize on page load 
    resize(); 
}); 

所以當項目的細節DIV達到的高度比更高。英雄半,它增加了一個類,在其中一個孩子身上設置了最大高度,這將.project-details的總高度恢復爲平等al或小於.hero-half。

但是,當我調整我的窗口強制文本推動項目細節高度過高,並觸發限制高度類,它只適用於屏幕寬度和高度加起來偶數時(無論是寬度和高度是偶數,或者都是奇數)。如果總數奇怪,則項目細節的outerHeight似乎計算錯誤。

問題是,我認爲,.project-details的outerHeight有時會在它被限制的文本高度之前計算在它的自然高度上,有時它會在應用該類並在文本高度之後進行計算受限制,因此將.project-細節高度降低迴可接受的範圍。

我試着添加超時延遲類的希望額外的時間將意味着outerHeight計算總是正確的,但它沒有區別。

我該如何改變這個JS代碼,以確保.project-details outerHeight始終在應用restrict-height類之前讀取高度?

和相關:爲什麼奇數像素尺寸在這裏有什麼作用?

回答

0

解決方案是在if/else循環之前添加一個復位來標準化div高度,即刪除可能首先更改其高度的額外類。

var $box = $(".project-summary"); 

// reset 
$box.removeClass("restrict-height"); 
$box.removeClass("is-expanded"); 

var winWidth = $(window).width(); 
var heroHeight = $(".hero-half").outerHeight(); 
var boxHeight = $(".project-details").outerHeight();