2014-03-05 28 views
0

匹配另一個元素我有下面的代碼爲標題介紹了相匹配的頁面上有兩個元素具有相同的高度:在元素上設置的高度使用JavaScript

//get sector sub navigation height 
$(function() { 

sectorHeight(); 

if(window.attachEvent) { 
    window.attachEvent('onresize', sectorHeight); 
} 
else if(window.addEventListener) { 
    window.addEventListener('resize', sectorHeight); 
} 

//get profile sub navigation height 
profileHeight(); 

if(window.attachEvent) { 
    window.attachEvent('onresize', profileHeight); 
} 
else if(window.addEventListener) { 
    window.addEventListener('resize', profileHeight); 
} 

}); 


function sectorHeight() { 
    var secHeight = $('#sector-content').height(); 
    $('.content-sub-nav').css('height', secHeight); 
} 

function profileHeight() { 
    var secHeight = $('.profile-article').height(); 
    $('.mod-profile-search').css('height', secHeight); 
} 

這個目前被稱爲兩個使用不同元素的不同頁面。我怎樣才能編輯這個只使用一個單獨的函數在頁面加載和調整大小時都被調用?

回答

1

或者,也許你可以使用這種方法:

function fixHeights(){ 
    $('.js-same-height').each(function(){ 
     var self = $(this); 
     var target = $(self.data('target')); 
     self.height(target.height()); 
    }); 
} 

應該在同一頁上的多個不同的單元工作。給動態元素類「js-same-height」和屬性「data-target =」.css-selector「」,其中「.css-selector」是你想要複製的元素的選擇器高度。

這是它如何在resize事件中使用:

$(window).on('resize', fixHeights); 

或:

$(window).on('resize', function(){ 
    fixHeights(); 
}); 
+0

這似乎是工作,我該如何使用這一個頁面大小調整? –

+0

您可以在屏幕大小調整時運行此功能,如更新後的答案。 –

+0

好吧,我的意思是說,它保留了窗口大小調整到另一個方向時的最高高度值。所以如果高度從600px開始,然後調整到800px,而以其他方式保持800px。希望這是有道理的。 –

0

我覺得你是匹配兩個高度。而不是採取這種方法,你可以做這樣的事情:

function makeCorrectHeights() { 
    var maxHeight = max($(".autoheight")); 
    $(".autoheight").css('height', maxHeight); 
} 

這可以在任何頁面調用,並與.autoheight類的那些,將調整到最大高度。

+0

這是一個正常的解決方案 –

相關問題