2017-03-04 81 views
0

這段代碼得到的.divone的高度(這是響應),並將它作爲邊距來.divtwo高度:獲取的動態變化的元素

var height = $(".divone").height(); 
    $('.divtwo').css({"margin-top": height + "px"}); 

我怎樣才能做到這一點height得到更新,隨時隨地瀏覽器窗口被調整大小和.divone的高度變化?

我加入這一行,但我並沒有在所有的工作:

$(window).on("resize", height) 

回答

2

jQuery的.on(String event, Function handler)至少需要兩個參數:event要聽成一個字符串,然後function到當事件觸發時執行。

function recalcDivTwo() { 
    var height = $('.divone').height(); 
    $('.divtwo').css({"margin-top": height + "px"}); 
} 

然後添加到您的document.ready處理程序:

$(window).on("resize", recalcDivTwo); 

您還可以定義處理函數中調用一個匿名函數:

$(window).on("resize", function() { 
    $('.divtwo').css({"margin-top": $('.divone').height() + "px"}); 
}); 

短期處理函數除了特定的事件處理以外,我沒有任何其他目的,因爲它不會污染全局名稱空間,而是使用匿名的內聯函數定義。

https://api.jquery.com/on/

+0

這個偉大的工程,非常感謝! – Groen91

+1

不客氣。花點時間閱讀關於您即將使用的內容的jQuery文檔。這是真正有據可查的。 – connexo

1
$(window).resize(func); 
Var func=function(){ 
var height = $(".divone").height(); 
    $('.divtwo').css({"margin-top": height + "px"}); 
}