2016-11-18 59 views
-1

這裏面是一個小提琴 - https://jsfiddle.net/t6tpxqco/18/的jQuery - 獲得元素的高度和高度適用於其他元素相同的父

我所試圖做的是一個要素「.right」的搶高度和應用內聯樣式到與其匹配的jQuery抓起.right的高度「左」:

<li class="first"> 
    <div class="left"></div> 
    <div class="right"> 
    <h1>Bear claw bear claw biscuit biscuit.</h1> 
    <p class="nfo">Bear claw bear claw biscuit biscuit bonbon candy canes chocolate chocolate cake gingerbread. Gummies chocolate bar dragée tootsie roll. Chocolate bar sweet roll oat cake bear claw dragée chocolate bar chocolate bar.</p> 
    <a href="" class="readMore">Read More</a> 
    </div> 
</li> 

<li class="second"> 
    <div class="left"></div> 
    <div class="right"> 
    <h1>Chocolate bar sweet roll oat cake bear claw dragée</h1> 
    <p class="nfo">Bear claw bear claw biscuit biscuit bonbon candy canes chocolate chocolate cake gingerbread. Gummies chocolate bar dragée tootsie roll. Chocolate bar sweet roll oat cake bear claw dragée chocolate bar chocolate bar.Pudding chupa chups soufflé sweet roll jelly jujubes cake chocolate cake. Tiramisu gummies pastry donut caramels. Tart pastry liquorice tiramisu.</p> 
    <a href="" class="readMore">Read More</a> 
    </div> 
</li> 

這裏是jQuery代碼我使用:

var pressHeight = $('.right').height(); 
$('.left').css({ 
    height: pressHeight 
}) 

所以問題是,它obvi擷取.first列表項目中.right元素的高度,並將該高度應用於所有.left元素。

但是,如果你看小提琴,每個.right元素是不同的大小。我需要做的是將.left(圖片)元素的高度與同一父列表項中的各自.right元素進行匹配。

所以爲了幫助簡化,我需要每個列表項中的圖片來匹配內容的高度。

我該怎麼做。

注:這是通過WordPress的迴路中產生,所以我不能添加的ID在列表項內容。

+0

這是一個非常棒的插件,用於匹配相同類的元素的高度。其響應準備。 http://brm.io/jquery-match-height/ – AndyWarren

+0

只要使用這個插件,它將完成你想要的任務,並且你可以設置任何數量的元素來匹配耳朵其他高度,只要他們有你的類正在打電話。 – AndyWarren

回答

2

嘗試單獨解決每一個元素:

$('.left').each(function() { 
    var $r = $(this).siblings('.right').first(); 
    var h = $r.height(); 
    $(this).css({ 
     height: h 
    }); 
}); 

這段代碼的作用是通過所有.left元素的循環。對於每一個,它通過使用.siblings('.right')發現兄弟姐妹.right類別。我包括一個.first()只是爲了安全,雖然我不指望有多個.right兄弟姐妹。

+0

你能解釋一下這段代碼嗎? – driconmax

+1

@driconmax是的!正在編輯,以提供更多的細節,因爲您評論c: – Santi

+0

完美!謝謝! – agon024

1

通過每個.right類只是想迭代,就像這樣:

$(".right").each(function() { 
    var rightHeight = $(this).height(); 
    $(this).prev().css("height",rightHeight); 
}); 

你得到每個.right元素的高度,然後應用高度與.left的CSS的高度。

查看結果here

0

是的,您需要通過這樣的項目itarate:

 $(document).ready(function(){ 

     var rightElem = $('.right'); 

     rightElem.each(function() { 
      var that = $(this), 
       height = that.outerHeight(), 
       left = that.siblings('.left'); 
      left.css({'height': height}) 
      }); 

     }); 
0

更重要的是,你並不需要的JavaScript(或jQuery的,對於這個問題)這個了!

在你的CSS,請將您的<li>元素display: flex(也就是你現在的.left.right的div不需要再被浮動),看看Flexbox的工作,它的魔力。

相關問題