我正在搜索一个容器来抓取像这样的匹配元素的填充..
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>
set_height
div 也可能是 fixed_height
或 dynamic_height
如何修改 jQuery 以搜索其中一个并在找到一个时停止,这样如果有多个,那么它只会获取它找到的第一个的值?
最佳答案
http://api.jquery.com/multiple-selector/
您可以传递类列表作为选择器。
var padding = 0;
var items = $( ".container" ).find( ".set_height, .fixed_height, .dynamic_height");
if (items.length) {
padding = items[0].style.paddingTop;
}
编辑
@segu 是对的(谢谢),但是仅仅调用 first()
是不够的,你必须检查 first().style
的结果是否为undefined
,因为如果没有找到结果,调用first().style.paddingTop
会触发Uncaught TypeError: Cannot read property 'paddingTop' of undefined
。我只是使用了 length
属性。
关于javascript - jQuery - 从元素获取 CSS 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53225061/