简体   繁体   English

jQuery-从元素获取CSS值

[英]jQuery - Get CSS value from element

I am searching a container to grab the padding of a matched element like this.. 我正在寻找一个容器来抓住这样一个匹配元素的填充。

 padding = $( ".container" ).find( ".set_height" ).css( "padding-top" ); console.log(padding); 
 .set_height { padding-top:50px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="section"> <div class="match_height"> Section 1 </div> </div> <div class="section"> <div class="match_height"> Section 2 </div> </div> <div class="section"> <div class="set_height"> Section 3 </div> </div> </div> 

The set_height div could also potentially be fixed_height or dynamic_height set_height div也可能是fixed_heightdynamic_height

How can I modify the jQuery to search for one of those and stop when it finds one, so if there are multiples then it will just grab the value for the first one it finds? 我该如何修改jQuery以搜索其中之一,并在找到一个时停止搜索,因此,如果有多个,那么它将仅获取所找到的第一个的值?

http://api.jquery.com/multiple-selector/ http://api.jquery.com/multiple-selector/

You can pass a list of classes as a selector. 您可以传递一个类列表作为选择器。

var padding = 0;
var items = $( ".container" ).find( ".set_height, .fixed_height, .dynamic_height");
if (items.length) {
    padding = items[0].style.paddingTop; 
}

EDIT 编辑

@segu is right (thanks), but it's not sufficient to just call first() , you have to check if the result of first().style is undefined , because calling first().style.paddingTop can trigger Uncaught TypeError: Cannot read property 'paddingTop' of undefined if no results are found. @segu是正确的(谢谢),但是仅调用first()不够的,您必须检查first().style的结果是否undefined ,因为调用first().style.paddingTop可以触发Uncaught TypeError: Cannot read property 'paddingTop' of undefined如果未找到结果,则Uncaught TypeError: Cannot read property 'paddingTop' of undefined I just used length property instead. 我只是使用length属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM