簡體   English   中英

獲取特定的內聯CSS樣式和樣式名稱

[英]Get specific Inline CSS Style And Style Name

我正在尋找一種從元素中獲取特定內聯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");

問題在於它只獲得樣式值,這就是問題,因為“background”也可能是“background-image”,或者“background-repeat-y”也可能是“background-repeat-x”。

字符串操作是這項工作的錯誤工具,我很驚訝其他答案使用它。 style元素是為此任務而設計的。

您可以通過查看element.style找到所有內聯樣式的列表。 該對象如下所示:

在此輸入圖像描述

您可以看到它包含彼此分離的每個內聯CSS規則。 這是一個非常短的現場演示 ,將此對象打印到控制台,以便您可以看到我的意思:

 var el = document.getElementById("thediv"); console.log(el.style); 
 <div id="thediv" style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div> 

該對象包含一個可迭代的規則列表(例如, 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); 
 <div id="thediv" style="background-color:red; display:block; background-size:cover; background-attachment:fixed; background-repeat:repeat-y; cursor:pointer; width:100%"></div> 

你可以這樣做:

$('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]);
    }
}

});

演示: http//jsfiddle.net/sx3psqvh/

我會做類似以下的事情:

$(document).ready(function(){
    var filteredStyles = $.grep($("div").attr("style").split(';'), function(style) {
        return style.indexOf("background") > -1;
    });
    console.log(filteredStyles);
});

http://jsfiddle.net/6he3hu6y/

你可以這樣做:

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);

首先,您獲得整個樣式屬性,然后包含由“;”分割的所有CSS屬性。 到數組,最后為數組的每個鍵尋找包含“背景”的值。 如果是這樣,只需將該值連接到變量,添加';' 在每個值的末尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM