2015-02-11 256 views
1

我有以下HTML塊:獲取元素屬性

<div class="container"> 
<div class="class" style="left:100px; top:0px"> 
<div class="class" style="left:200px; top:0px"> 
<div class="class" style="left:200px; top:100px"> 
</div> 

我需要每一個從內聯CSS的位置,我該怎麼辦呢?

我知道我不能使用.attr()或js getAttribute,因爲這會返回整個樣式塊。

我的理想,我想是這樣的:

$(".container> .class").each(function(){ 
    var context = $(this); 
    var thisLeft = context.left; // which I know is incorrect 
} 

這可能嗎? JQuery的或香草細

+1

'$( '... ')的CSS(' 左')'。請參閱http://api.jquery.com/css/#css1 – Phil 2015-02-11 10:20:03

回答

3

在jQuery中,你會做$(this).css('left')

$(".container> .class").each(function(){ 
    var thisLeft = $(this).css('left'); 
}); 

正如@Fred所說,this.style.left使用並不關心使用樣式塊或外部CSS文件應用於元素的樣式,所以只需使用$.fn.css方法。

+1

請注意,'style'屬性只考慮內聯樣式。例如,它不會考慮通過外部樣式表應用的樣式。 – 2015-02-11 10:21:56

+0

@FrédéricHamidi是不是**完全** OP要求什麼? – Phil 2015-02-11 10:22:27

+0

@菲爾,那不是我讀書的方式。提問者說*我需要獲取每個[元素] *的位置,但該位置不僅取決於內聯樣式。誠然,這個問題的前提可能首先是有缺陷的。 – 2015-02-11 10:23:35

2

Anoter解決方案是使用jQuery的map並得到所有喜歡的值:

var pos = $(".container > .class").map(function() { 
 
    return { 
 
    left: $(this).css("left"), 
 
    top: $(this).css("top"), 
 
    right: $(this).css("top"), 
 
    bottom: $(this).css("bottom"), 
 
    } 
 
}).get(); 
 

 
console.log(pos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div class="class" style="left:100px; top:0px"></div> 
 
    <div class="class" style="left:200px; top:0px"></div> 
 
    <div class="class" style="left:200px; top:100px"></div> 
 
</div>