2016-12-13 82 views
1

我有3個圖像塊,其上有文本。以下是3箇中的一個的樣子。獲取每個元素獲取高度並將其應用爲邊緣頂部

<div class="lp"> 
    <h2 class="align-vert"> 
     This is my title 
    </h2> 
</div> 

我想拿到冠軍height(); jQuery中,並將其應用到aligh-v。我嘗試了下面的jQuery代碼,但它不起作用。

jQuery.each(jQuery('.js-vert'), function() { 
    jQuery(this).css({ 
     "margin-top": '"' + jQuery('.js-vert').height() + '"' 
    }); 
}); 
+0

什麼是'.js文件 - 翻轉?它似乎不包含在您的DOM中。 –

回答

5

的問題是,因爲你需要使用each()方法中的this引用來引用當前元素。按照現狀,您的代碼將調用height()整個元素集合,這意味着只返回第一個元素的高度。你的字符串連接的語法也有點關閉。試試這個:

$('.js-vert').each(function() { 
    $(this).css("margin-top", $(this).height()); 
}); 

另外請注意,這可以通過徹底消除了each()循環和傳遞功能的css()方法返回所需的值來進行更簡潔:

$('.js-vert').css('margin-top', function() { 
    return $(this).height(); 
}); 
+1

不知道你可以傳遞一個函數到那個方法。真棒! +1 – War10ck

+0

不錯,謝謝@Rory像一個魅力:) – Radu033