我正在寻找一种从元素中获取特定内联CSS样式的方法,包括样式名称本身和值。
我有一个包含像这样的不同内联样式的元素。
<div style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>
我想获取该元素的样式(包括样式名称本身和值),但是只有那些与“背景”有关的样式,而忽略诸如“显示,光标,宽度”之类的其他样式。
因此,要使用jQuery获得样式,我只需执行此操作
$("div").attr("style");
这将返回该元素的所有样式,包括我不想要的样式。我正在寻找的解决方案将返回类似这样的内容,它忽略了与“ background-”无关的其他样式
background-color:red; background-size:cover; background-attachment:fixed; background-repeat:repeat-y;
我知道我可以得到像这样的个人风格
$("div").css("background");
$("div").css("background-size");
这样做的问题在于,它仅获得样式值,这就是一个问题,因为“背景”也可以是“背景图像”,或者“背景重复y”也可以是“背景重复x”。
您可以执行以下操作:
$('div').each(function() {
style_arr=$(this).attr("style").split(';');
for(i=0;i<style_arr.length;i++) {
if(style_arr[i].indexOf('background')!=-1) {
console.log(style_arr[i]);
}
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句