2011-03-09 85 views
0

如何才能在jquery中選擇樣式爲「right:200px」的div?選擇特定的內聯樣式

例子:

<div class="test" style="position:absolute; right:200px; top:10px;"><p>Hello</p></div> 
<div class="test" style="position:absolute; right:300px; top:20px;"><p>Hello</p></div> 
<div class="test" style="position:absolute; right:400px; top:70px;"><p>Hello</p></div> 
<div class="test" style="position:absolute; right:200px; top:40px;"><p>Hello</p></div> 
<div class="test" style="position:absolute; right:400px; top:100px;"><p>Hello</p></div> 
<div class="test" style="position:absolute; right:200px; top:140px;"><p>Hello</p></div> 


var div200 = $('.test').css('right'); 

我不知道如何與只選擇div的「右:​​200像素」。 我是jquery的新手。我很努力,但沒有成功:

阿希姆

回答

3
var div200 = $('.test').filter(function(){ 
    return $(this).css('right') == "200px"; 
}); 
+0

這是這麼多比所有的字符串操作我一直在尋找這樣做更容易... +1,純真棒! :) – 2011-03-09 00:57:54

+0

嗨大衛,這是真的短可讀 - 感謝解決方案。那麼,我必須對給定的內聯風格進行maniuplate,我知道用css避免內聯風格會更好。但jquery沒有問題。 – 2011-03-10 15:27:02

0

我不知道如何選擇只能用div的「右:​​200像素」。

這可能在某種程度上是可能的,但它有點反對jQuery和CSS應該如何工作。考慮將實際的位置信息到類:

div.p1 { position:absolute; right:200px; top:10px; } 
div.p2 { position:absolute; right:300px; top:20px; } 
.... 
etc. 

並具有簡化的div結構:

<div class="test p1"><p>Hello</p></div> 
<div class="test p2"><p>Hello</p></div> 
etc. 

,然後解決每個div都使用

var div1 = $('.test.p1'); 
var div2 = $('.test.p2'); 
etc. 

也讓你從特定的獨立像200px這樣的數字 - 你改變它的唯一地方是在樣式表中。

2
$('.test').filter(function(){ 
    return $(this).css('right') == "200px"; 
}).addClass('selected'); 

See example.