2012-02-06 93 views
1

我不確定描述此的最佳方式。但是我找到了圖像寬度,如果它小於200px,它會向父div應用200以下的類。jquery < than and > than .width

$('.content').find('img').each(function() { 
    var $this = $(this), width = $this.width(); 
     if (width < 200) { 
     $(this).parents('.container').addClass('under-200'); 
     } 
}); 

CSS:.container.under-200 {width: 200px}

這工作得很好,但我在與應用的寬度較大的圖像困難。

因此,對於600像素的圖像,jquery將600px寬度應用於父div,或者434px圖像將434px寬度應用於父div。

+1

@ Cadence96如果你只想要直接父母,是的,它是父母()。如果你想繼續向上,它是父母()(或最接近的()) – 2012-02-06 11:53:18

回答

1

試試這個:

$(this).parents('.container').css("width", width); 

此外,使用.closest()代替.parents()

.parents()將通過DOM一直到根元素,HTML和THEN根據您的選擇器篩選結果。另一方面,.closest()只要找到匹配就會停止。

你可以煮所有代碼到一個單一的線路:

$(this).closest('.container').css("width", (width < 200 ? 200 : width)); 

希望這有助於!

+0

簡單易懂!非常感謝你。 '.closest()'必須更快''.parents()'。再次感謝。 – uriah 2012-02-06 12:07:34

0

width()setter form,所以你可以寫:

$(".content img").each(function() { 
    var $this = $(this), 
     $containers = $this.parents(".container"), 
     width = $this.width(); 
    if (width < 200) { 
     $containers.addClass("under-200"); // Set class. 
    } else { 
     $containers.width(width);   // Set width. 
    } 
}); 
+0

感謝您的幫助Frédéric,非常容易。 – uriah 2012-02-06 12:08:51

0

也許你應該解析 '寬度' 爲int?讓

if (width < 200) 

作品,如果寬度確實小於200。我可以想像,因爲寬度是一個字符串,它現在總是返回true只返回true?

+0

['.width()'](http://api.jquery.com/width/)返回一個數字.. – 2012-02-06 12:01:16

+0

'.width()'返回一個數字。 (第二個動作)*在數學計算中需要使用元素的寬度時,推薦使用.width()方法。* http://api.jquery.com/width/ – Joseph 2012-02-06 12:01:34

+0

我知道它不會返回任何單位,但是它總是一個整數,即從來沒有一個字符串或浮動?浮動不應該是一個問題,但。 – 2012-02-06 12:25:49

相關問題