我正在寻找一种从元素中获取特定内联css样式的方法,包括样式名称本身和值。
我有一个包含不同内联样式的元素。
<div style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>
我想获得该元素的样式(包括样式名称本身和值),但只有那些与&#34;背景&#34;并忽略其他像&#34;显示,光标,宽度&#34;等等
所以要使用jQuery获取样式,我只需执行此操作
$("div").attr("style");
这将返回元素的所有样式,包括我不想要的样式。我正在寻找的解决方案将返回类似这样的内容,忽略了与“#34;背景 - &#34;
无关的其他风格background-color:red; background-size:cover; background-attachment:fixed; background-repeat:repeat-y;
我知道我可以得到像这样的个人风格
$("div").css("background");
$("div").css("background-size");
问题在于它只获得了样式值,这就是问题,因为&#34;背景&#34;也可以是&#34; background-image&#34;,或&#34; background-repeat-y&#34;也可以是&#34; background-repeat-x&#34;。
答案 0 :(得分:2)
字符串操作是这项工作的错误工具,我很惊讶其他答案使用它。 style元素是为此任务而设计的。
您可以通过查看element.style
找到所有内联样式的列表。该对象如下所示:
您可以看到它包含彼此分开的每个内联CSS规则。这是一个非常简短的现场演示,它将此对象打印到控制台,以便您可以看到我的意思:
var el = document.getElementById("thediv");
console.log(el.style);
&#13;
<div id="thediv" style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>
&#13;
该对象包含可迭代的规则列表(例如element.style[0]
为background-color
),以及字典,以便您可以按名称获取特定规则。然后,您应该可以轻松过滤此列表,以获取您正在寻找的任何特定规则。
这是一个实时演示,向您展示如何获取其中包含字符串background
的所有规则(打开控制台)。它将结果放入一组易于访问的名称和值对中:
var el = document.getElementById("thediv");
var result = [];
for (var i = 0; i < el.style.length; i++) {
if (el.style[i].indexOf("background") !== -1) {
result.push({name: el.style[i], value: el.style[el.style[i]]});
}
}
console.log(result);
&#13;
<div id="thediv" style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div>
&#13;
答案 1 :(得分:1)
您可以这样做:
$('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]);
}
}
});
答案 2 :(得分:0)
我会做以下事情:
$(document).ready(function(){
var filteredStyles = $.grep($("div").attr("style").split(';'), function(style) {
return style.indexOf("background") > -1;
});
console.log(filteredStyles);
});
答案 3 :(得分:0)
你可以这样做:
var style = $("div").attr("style");
var arrayStyle = style.split(';');
var backgroundStyles = '';
for (i = 0; i < arrayStyle.length; ++i) {
if (arrayStyle[i].indexOf("background") >= 0) {
backgroundStyles+=arrayStyle[i]+';';
}
}
console.log(backgroundStyles);
首先,您获得整个样式属性, 然后包括由&#34 ;;&#34;分割的所有CSS属性。到一个数组,最后为数组的每个键寻找包含&#34; background&#34;的值。如果是这样,只需将该值连接到变量,添加&#39;;&#39;在每个值的末尾。