2015-02-11 196 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>