2011-12-15 46 views
3

我有元素有雜項高度。根據第一個塊,我需要爲其他元素添加一些margin-top。我被用於jQuery高度屬性的這個動作,但它不起作用。你可以幫我嗎?使用jQuery添加基於其他元素高度的頂部邊距

這是我的代碼:

$(document).ready(function(){ 
    if ($('.post_discussion_header').height(79) + 'px'){ 
     $('.no_0').css('margin-top','110px'); 
     } 
    }); 
}); 

TIA。

+0

您的if語句錯了,您想要驗證的是什麼? – 2011-12-15 08:32:17

回答

2

你如果說法是錯誤的,應該是

if ($('.post_discussion_header').height() == 79){ 

但是你可以考慮使用偏移高度返回元素的高度,包括邊框和填充,如果有,但不是利潤https://developer.mozilla.org/en/DOM/element.offsetHeight

if (parseInt($('.post_discussion_header')[0].offsetHeight,10) == 79){ 

編輯:加入parseInt函數以 「79px」 轉換爲79用於比較http://www.w3schools.com/jsref/jsref_parseInt.asp

你也有一個太多});在你的代碼中。第5行應該是}

+0

是的,它的工作,很多thx,我是你的債務人:) – Lukas 2011-12-15 08:55:05

0

$('.post_discussion_header').height(79)將高度.post_discussion_header設置爲79,並返回.post_discussion_header。然後您將該頭與「px」連接起來。您的代碼將評估爲類似

if('[object Object]px') { 
    ... 
} 

顯然,這不是您的意圖。問題是,你的意圖是什麼?你想檢查什麼條件?

您的代碼中還有太多太多的});

+0

我有.post_discussion_header女巫沒有選定的高度。這個屬性在我的標題有一兩行時設置。如果它有一行少於79px,並且它溢出到.no_0 bcs .post_discussion_header設置顯示在固定... :( – Lukas 2011-12-15 08:43:43

0

嘗試使用.css("height")這應該爲你做!
但是不要忘記,如果您嘗試將高度添加到div元素的實際高度,jQuery.css(「height」)將返回「23px」,因此您必須先刪除「px」,然後才能添加某個整數值。

2
 

$(document).ready(function(){ 
    if ($('.post_discussion_header').height() == 79) { 
     $('.no_0').css('margin-top','110px'); 
    } 
}); 
 
相關問題