คุณอ่านค่ากฎ CSS ด้วย JavaScript ได้อย่างไร?


116

ฉันต้องการส่งคืนสตริงที่มีเนื้อหาทั้งหมดของกฎ CSS เช่นเดียวกับรูปแบบที่คุณเห็นในสไตล์อินไลน์ ฉันต้องการที่จะทำได้โดยที่ไม่รู้ว่ามีอะไรอยู่ในกฎใดกฎหนึ่งดังนั้นฉันจึงไม่สามารถดึงมันออกมาตามชื่อสไตล์ได้ (เช่น.style.widthฯลฯ )

CSS:

.test {
    width:80px;
    height:50px;
    background-color:#808080;
}

รหัสจนถึงตอนนี้:

function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
            //this is where I can collect the style information, but how?
        }
    }
}
getStyle('.test')

โปรดตรวจสอบสิ่งนี้ด้วย stackoverflow.com/questions/53592919/…
Mithilesh Kumar

คำตอบ:


91

ดัดแปลงจากที่นี่สร้างจากคำตอบของ scunliffe:

function getStyle(className) {
    var cssText = "";
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var x = 0; x < classes.length; x++) {        
        if (classes[x].selectorText == className) {
            cssText += classes[x].cssText || classes[x].style.cssText;
        }         
    }
    return cssText;
}

alert(getStyle('.test'));

11
โปรดทราบว่า className ต้องตรงกับตัวเลือกที่ใช้ในไฟล์ CSS ทุกประการ ตัวอย่างเช่น getStyle (". article a") จะไม่พบอะไรเลยหากมีการอธิบายสไตล์เช่นนี้ ".article a, article a: hover {color: #ccc;}"
Vilius Paulauskas

1
สิ่งนี้ใช้ไม่ได้ใน chrome แต่ใช้ได้กับ firefox ปัญหาอาจเกิดจากอะไร ??
Johnydep

13
หากมีหลายสไตล์ชีทคุณก็จะต้องวนซ้ำด้วยเช่นกันสำหรับ (var i = 0; i <document.styleSheets.length; i ++) {var s = document.styleSheets [i];}
surya

@surya ดูคำตอบของฉันสำหรับโซลูชันการทำงานแบบเต็มรูปแบบ
เพื่อน

2
@Johnydep var classesควรอยู่document.styleSheets[0].rules[0].cssRulesใน Chrome นี่อาจเป็นการเพิ่ม (อย่างสร้างสรรค์) ให้กับ shim ในคำตอบ
Henrik Christensen

23

เนื่องจากคำตอบที่ยอมรับจาก "nsdel" สามารถใช้ได้กับสไตล์ชีตเดียวในเอกสารเท่านั้นนี่จึงเป็นโซลูชันการทำงานแบบเต็มรูปแบบที่ปรับเปลี่ยนแล้ว:

    /**
     * Gets styles by a classname
     * 
     * @notice The className must be 1:1 the same as in the CSS
     * @param string className_
     */
    function getStyle(className_) {

        var styleSheets = window.document.styleSheets;
        var styleSheetsLength = styleSheets.length;
        for(var i = 0; i < styleSheetsLength; i++){
            var classes = styleSheets[i].rules || styleSheets[i].cssRules;
            if (!classes)
                continue;
            var classesLength = classes.length;
            for (var x = 0; x < classesLength; x++) {
                if (classes[x].selectorText == className_) {
                    var ret;
                    if(classes[x].cssText){
                        ret = classes[x].cssText;
                    } else {
                        ret = classes[x].style.cssText;
                    }
                    if(ret.indexOf(classes[x].selectorText) == -1){
                        ret = classes[x].selectorText + "{" + ret + "}";
                    }
                    return ret;
                }
            }
        }

    }

หมายเหตุ: ตัวเลือกจะต้องเหมือนกับใน CSS


global_เป็นเพียงนามแฝงสำหรับวัตถุหน้าต่าง ฉันได้แก้ไขข้อมูลโค้ดแล้ว ตอนนี้น่าจะใช้ได้แล้ว
เพื่อน

3
รหัสของคุณล้มเหลวหากสไตล์ชีตไม่มีกฎหรือ cssRules (ซึ่งสามารถเกิดขึ้นได้!) เพิ่มถ้า (! คลาส) ดำเนินการต่อ; หลังจาก var คลาส = styleSheets [i] .rules || StyleSheets [ผม] .cssRules; var classLength = คลาสความยาว; ดูการแก้ไขของฉัน
kofifus

1
ใช้งานได้ แต่ควรส่งคืนวัตถุแทนสตริง
brauliobo

@kofifus เพิ่มแนวทางของคุณแล้ว
เพื่อน

โปรดทราบว่าสิ่งนี้ใช้ไม่ได้ตั้งแต่ GC รุ่น 64.0: stackoverflow.com/questions/48753691/…
Shalev Levi

18

โซลูชัน 1 (CROSS-BROWSER)

function GetProperty(classOrId,property)
{ 
    var FirstChar = classOrId.charAt(0);  var Remaining= classOrId.substring(1);
    var elem = (FirstChar =='#') ?  document.getElementById(Remaining) : document.getElementsByClassName(Remaining)[0];
    return window.getComputedStyle(elem,null).getPropertyValue(property);
}

alert( GetProperty(".my_site_title","position") ) ;

โซลูชันที่ 2 (CROSS-BROWSER)

function GetStyle(CLASSname) 
{
    var styleSheets = document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        if (styleSheets[i].rules ) { var classes = styleSheets[i].rules; }
        else { 
            try {  if(!styleSheets[i].cssRules) {continue;} } 
            //Note that SecurityError exception is specific to Firefox.
            catch(e) { if(e.name == 'SecurityError') { console.log("SecurityError. Cant readd: "+ styleSheets[i].href);  continue; }}
            var classes = styleSheets[i].cssRules ;
        }
        for (var x = 0; x < classes.length; x++) {
            if (classes[x].selectorText == CLASSname) {
                var ret = (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText ;
                if(ret.indexOf(classes[x].selectorText) == -1){ret = classes[x].selectorText + "{" + ret + "}";}
                return ret;
            }
        }
    }
}

alert( GetStyle('.my_site_title') );

6

ความแตกต่างบางประการของเบราว์เซอร์ที่ควรทราบ:

ให้ CSS:

div#a { ... }
div#b, div#c { ... }

และจากตัวอย่างของ InsDel คลาสจะมี2 คลาสใน FF และ 3 คลาสใน IE77

ตัวอย่างของฉันแสดงให้เห็นสิ่งนี้:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <style>
    div#a { }
    div#b, div#c { }
    </style>
    <script>
    function PrintRules() {
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules
        for(var x=0;x<rules.length;x++) {
            document.getElementById("rules").innerHTML += rules[x].selectorText + "<br />";
        }
    }
    </script>
</head>
<body>
    <input onclick="PrintRules()" type="button" value="Print Rules" /><br />
    RULES:
    <div id="rules"></div>
</body>
</html>

4

นี่คือรหัสสำหรับวนซ้ำตามกฎทั้งหมดในหน้า:

function iterateCSS(f) {
  for (const styleSheet of window.document.styleSheets) {
    const classes = styleSheet.rules || styleSheet.cssRules;
    if (!classes) continue;

    for (const cssRule of classes) {
      if (cssRule.type !== 1 || !cssRule.style) continue;
      const selector = cssRule.selectorText, style=cssRule.style;
      if (!selector || !style.cssText) continue;
      for (let i=0; i<style.length; i++) {
        const propertyName=style.item(i);
        if (f(selector, propertyName, style.getPropertyValue(propertyName), style.getPropertyPriority(propertyName), cssRule)===false) return;
      }
    }
  }
}

iterateCSS( (selector, propertyName, propertyValue, propertyPriority, cssRule) => {
  console.log(selector+' { '+propertyName+': '+propertyValue+(propertyPriority==='important' ? ' !important' : '')+' }');
});


2
function getStyle(className) {
    document.styleSheets.item("menu").cssRules.item(className).cssText;
}
getStyle('.test')

หมายเหตุ: "menu" คือรหัสองค์ประกอบที่คุณใช้ CSS "className" ชื่อคลาส css ที่เราต้องการเพื่อรับข้อความ


แน่ใจหรือว่าใช้งานได้ (AFAIK itemวิธีนี้ใช้ดัชนีจำนวนเต็มไม่ใช่ className)
Julien Kronegg

เรื่องไร้สาระสมบูรณ์
tnt-rox

2

ฉันไม่พบคำแนะนำใด ๆ ที่จะใช้งานได้จริง นี่คือสิ่งที่แข็งแกร่งกว่าที่ทำให้ระยะห่างเป็นปกติเมื่อค้นหาชั้นเรียน

//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
    function normalize(str) {
        if (!str)  return '';
        str = String(str).replace(/\s*([>~+])\s*/g, ' $1 ');  //Normalize symbol spacing.
        return str.replace(/(\s+)/g, ' ').trim();           //Normalize whitespace
    }
    function split(str, on) {               //Split, Trim, and remove empty elements
        return str.split(on).map(x => x.trim()).filter(x => x);
    }
    function containsAny(selText, ors) {
        return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
    }
    return function (selector) {
        const logicalORs = split(normalize(selector), ',');
        const sheets = Array.from(window.document.styleSheets);
        const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
        const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
        return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
    };
})();

นี่คือการใช้งานจริงจากคอนโซล Chrome

ใส่คำอธิบายภาพที่นี่


1
นี่คือกลไกของคำตอบทั้งหมดในหน้านี้ ฉันจะไปไกลถึงที่จะบอกว่านี่ควรจะเป็นใน github
Jacksonkr

สิ่งนี้ใช้ไม่ได้ใน IE11 เนื่องจากไม่รองรับ Array.map () ที่มีไวยากรณ์ที่ให้มา ฉันขอแนะนำให้เปลี่ยนเป็นฟังก์ชันเก่า () {return xxx; } ไวยากรณ์เพื่อความเข้ากันได้ที่ดีขึ้น ไม่งั้นตอบโจทย์มาก!
Demonblack

1
ฉันแก้ไขสิ่งนี้ให้ทำงานกับ IE11 (เช่น ES5) นี่คือ JSFiddle พร้อมทุกสิ่งที่คุณต้องการ: jsfiddle.net/xp5r8961
Demonblack

1

ฉันสร้างฟังก์ชันตัวช่วยที่คล้ายกันซึ่งแสดงรูปแบบที่ไม่จำเป็นสำหรับหน้านี้ ผนวก<div>กับเนื้อหาที่แสดงรูปแบบทั้งหมดที่ไม่ได้ใช้

(ใช้กับคอนโซล firebug)

(function getStyles(){var CSSrules,allRules,CSSSheets, unNeeded, currentRule;
CSSSheets=document.styleSheets;

for(j=0;j<CSSSheets.length;j++){
for(i=0;i<CSSSheets[j].cssRules.length;i++){
    currentRule = CSSSheets[j].cssRules[i].selectorText;

    if(!document.querySelectorAll(currentRule).length){ 
       unNeeded+=CSSSheets[j].cssRules[i].cssText+"<br>"; 
  }       
 }
}

docBody=document.getElementsByTagName("body")[0];
allRulesContainer=document.createElement("div");
docBody.appendChild(allRulesContainer);
allRulesContainer.innerHTML=unNeeded+isHover;
return false
})()

1

ปรับคำตอบของ julmot เพื่อให้ได้ผลลัพธ์ที่สมบูรณ์ยิ่งขึ้น วิธีนี้จะส่งคืนสไตล์ที่คลาสเป็นส่วนหนึ่งของตัวเลือก

//Get all styles where the provided class is involved
//Input parameters should be css selector such as .myClass or #m
//returned as an array of tuples {selectorText:"", styleDefinition:""}
function getStyleWithCSSSelector(cssSelector) {
    var styleSheets = window.document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    var arStylesWithCSSSelector = [];

    //in order to not find class which has the current name as prefix
    var arValidCharsAfterCssSelector = [" ", ".", ",", "#",">","+",":","["];

    //loop through all the stylessheets in the bor
    for(var i = 0; i < styleSheetsLength; i++){
        var classes = styleSheets[i].rules || styleSheets[i].cssRules;
        var classesLength = classes.length;
        for (var x = 0; x < classesLength; x++) {
            //check for any reference to the class in the selector string
            if(typeof classes[x].selectorText != "undefined"){
                var matchClass = false;

                if(classes[x].selectorText === cssSelector){//exact match
                    matchClass=true;
                }else {//check for it as part of the selector string
                    //TODO: Optimize with regexp
                    for (var j=0;j<arValidCharsAfterCssSelector.length; j++){
                        var cssSelectorWithNextChar = cssSelector+ arValidCharsAfterCssSelector[j];

                        if(classes[x].selectorText.indexOf(cssSelectorWithNextChar)!=-1){
                            matchClass=true;
                            //break out of for-loop
                            break;
                        }
                    }
                }

                if(matchClass === true){
                    //console.log("Found "+ cssSelectorWithNextChar + " in css class definition " + classes[x].selectorText);
                    var styleDefinition;
                    if(classes[x].cssText){
                        styleDefinition = classes[x].cssText;
                    } else {
                        styleDefinition = classes[x].style.cssText;
                    }
                    if(styleDefinition.indexOf(classes[x].selectorText) == -1){
                        styleDefinition = classes[x].selectorText + "{" + styleDefinition + "}";
                    }
                    arStylesWithCSSSelector.push({"selectorText":classes[x].selectorText, "styleDefinition":styleDefinition});
                }
            }
        }
    }
    if(arStylesWithCSSSelector.length==0) {
        return null;
    }else {
        return arStylesWithCSSSelector;    
    }
}

นอกจากนี้ฉันได้สร้างฟังก์ชันที่รวบรวมคำจำกัดความสไตล์ css ไปยังทรีย่อยของโหนดรูทที่คุณให้ (ผ่านตัวเลือก jquery)

function getAllCSSClassDefinitionsForSubtree(selectorOfRootElement){
    //stack in which elements are pushed and poped from
    var arStackElements = [];
    //dictionary for checking already added css class definitions
    var existingClassDefinitions = {}

    //use jquery for selecting root element
    var rootElement = $(selectorOfRootElement)[0];
    //string with the complete CSS output
    var cssString = "";

    console.log("Fetching all classes used in sub tree of " +selectorOfRootElement);
    arStackElements.push(rootElement);
    var currentElement;

    while(currentElement = arStackElements.pop()){
        currentElement = $(currentElement);
        console.log("Processing element " + currentElement.attr("id"));

        //Look at class attribute of element 
        var classesString = currentElement.attr("class");
        if(typeof classesString != 'undefined'){
            var arClasses = classesString.split(" ");

            //for each class in the current element
            for(var i=0; i< arClasses.length; i++){

                //fetch the CSS Styles for a single class. Need to append the . char to indicate its a class
                var arStylesWithCSSSelector = getStyleWithCSSSelector("."+arClasses[i]);
                console.log("Processing class "+ arClasses[i]);

                if(arStylesWithCSSSelector != null){
                    //console.log("Found "+ arStylesWithCSSSelector.length + " CSS style definitions for class " +arClasses[i]);
                    //append all found styles to the cssString
                    for(var j=0; j< arStylesWithCSSSelector.length; j++){
                        var tupleStyleWithCSSSelector = arStylesWithCSSSelector[j];

                        //check if it has already been added
                        if(typeof existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] === "undefined"){
                            //console.log("Adding " + tupleStyleWithCSSSelector.styleDefinition);
                            cssString+= tupleStyleWithCSSSelector.styleDefinition;
                            existingClassDefinitions[tupleStyleWithCSSSelector.selectorText] = true;
                        }else {
                            //console.log("Already added " + tupleStyleWithCSSSelector.styleDefinition);
                        }
                    }
                }
            }
        }
        //push all child elments to stack
        if(currentElement.children().length>0){
            arStackElements= arStackElements.concat(currentElement.children().toArray());
        }
    }

    console.log("Found " + Object.keys(existingClassDefinitions).length + " CSS class definitions");
    return cssString;
}

โปรดทราบว่าหากมีการกำหนดคลาสหลายครั้งด้วยตัวเลือกเดียวกันฟังก์ชันข้างต้นจะเลือกเฉพาะฟังก์ชันแรกเท่านั้น โปรดทราบว่าตัวอย่างใช้ jQuery (แต่มีการเขียน cab ค่อนข้างง่ายเพื่อไม่ให้ใช้งาน)


1
จะเป็นการดีที่จะมีโซลูชันที่ไม่ใช่ jquery (และ jsfiddle .. )
kofifus

0

// ทำงานใน IE ไม่แน่ใจเกี่ยวกับเบราว์เซอร์อื่น ...

alert(classes[x].style.cssText);

0

เวอร์ชันนี้จะแสดงสไตล์ชีททั้งหมดในหน้า สำหรับความต้องการของฉันสไตล์มักจะอยู่ในช่วงที่ 2 ถึงสุดท้ายจาก 20 สไตล์ชีทดังนั้นฉันจึงตรวจสอบย้อนหลัง

    var getStyle = function(className){
        var x, sheets,classes;
        for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){
            classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;
            for(x=0;x<classes.length;x++) {
                if(classes[x].selectorText===className) {
                    return  (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText);
                }
            }
        }
        return false;
    };

0

ฉันเพิ่มการส่งคืนของวัตถุโดยที่แอตทริบิวต์ถูกแยกวิเคราะห์สไตล์ / ค่า:

var getClassStyle = function(className){
    var x, sheets,classes;
    for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){
        classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;
        for(x=0;x<classes.length;x++) {
            if(classes[x].selectorText===className){
                classStyleTxt = (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText).match(/\{\s*([^{}]+)\s*\}/)[1];
                var classStyles = {};
                var styleSets = classStyleTxt.match(/([^;:]+:\s*[^;:]+\s*)/g);
                for(y=0;y<styleSets.length;y++){
                    var style = styleSets[y].match(/\s*([^:;]+):\s*([^;:]+)/);
                    if(style.length > 2)
                        classStyles[style[1]]=style[2];
                }
                return classStyles;
            }
        }
    }
    return false;
};

style.cssText.match(...).1เป็นโมฆะหรือไม่ใช่วัตถุ
เพื่อน

Uncaught ReferenceError: classStyleTxt is not defined
Jacksonkr

0

ฉันสร้างเวอร์ชันที่ค้นหาสไตล์ชีตทั้งหมดและส่งคืนรายการที่ตรงกันเป็นวัตถุคีย์ / ค่า คุณยังสามารถระบุstartWithเพื่อจับคู่สไตล์ลูกได้

getStylesBySelector('.pure-form-html', true);

ผลตอบแทน:

{
    ".pure-form-html body": "padding: 0; margin: 0; font-size: 14px; font-family: tahoma;",
    ".pure-form-html h1": "margin: 0; font-size: 18px; font-family: tahoma;"
}

จาก:

.pure-form-html body {
    padding: 0;
    margin: 0;
    font-size: 14px;
    font-family: tahoma;
}

.pure-form-html h1 {
    margin: 0;
    font-size: 18px;
    font-family: tahoma;
}

รหัส:

/**
 * Get all CSS style blocks matching a CSS selector from stylesheets
 * @param {string} className - class name to match
 * @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)
 * @example getStylesBySelector('pure-form .pure-form-html ')
 * @returns {object} key/value object containing matching styles otherwise null
 */
function getStylesBySelector(className, startingWith) {

    if (!className || className === '') throw new Error('Please provide a css class name');

    var styleSheets = window.document.styleSheets;
    var result = {};

    // go through all stylesheets in the DOM
    for (var i = 0, l = styleSheets.length; i < l; i++) {

        var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];

        // go through all classes in each document
        for (var x = 0, ll = classes.length; x < ll; x++) {

            var selector = classes[x].selectorText || '';
            var content = classes[x].cssText || classes[x].style.cssText || '';

            // if the selector matches
            if ((startingWith && selector.indexOf(className) === 0) || selector === className) {

                // create an object entry with selector as key and value as content
                result[selector] = content.split(/(?:{|})/)[1].trim();
            }
        }
    }

    // only return object if we have values, otherwise null
    return Object.keys(result).length > 0 ? result : null;
}

ฉันใช้สิ่งนี้ในการผลิตเป็นส่วนหนึ่งของโครงการรูปแบบบริสุทธิ์ หวังว่าจะช่วยได้


0

ฉันประสบปัญหาเดียวกัน และด้วยความช่วยเหลือของผู้ชายฉันได้พบกับโซลูชันที่ชาญฉลาดจริงๆที่ช่วยแก้ปัญหานั้นได้ทั้งหมด (ทำงานบนโครเมี่ยม)

แยกภาพทั้งหมดออกจากเครือข่าย

 function AllImagesUrl (domain){
  return  performance.getEntries()
    .filter( e=> 
       e.initiatorType == "img" &&
       new RegExp(domain).test(e.name) 
    )
  .map( e=> e.name.replace('some cleaning work here','') ) ```

0
const getStyle = query => [...document.querySelector(query).computedStyleMap().entries()].map(e=>(e[1]+=[],e)).map(e=>e.join`:`+';').join`\n`

ในหนึ่งบรรทัดพิมพ์ css ที่สร้างขึ้นสำหรับแบบสอบถามใด ๆ


-2

จากคำตอบของ @dude สิ่งนี้ควรส่งคืนรูปแบบที่เกี่ยวข้องในวัตถุตัวอย่างเช่น:

.recurly-input {                                                                                                                                                                             
  display: block;                                                                                                                                                                            
  border-radius: 2px;                                                                                                                                                                        
  -webkit-border-radius: 2px;                                                                                                                                                                
  outline: 0;                                                                                                                                                                                
  box-shadow: none;                                                                                                                                                                          
  border: 1px solid #beb7b3;                                                                                                                                                                 
  padding: 0.6em;                                                                                                                                                                            
  background-color: #f7f7f7;                                                                                                                                                                 
  width:100%;                                                                                                                                                                                
}

สิ่งนี้จะกลับมา:

backgroundColor:
"rgb(247, 247, 247)"
border
:
"1px solid rgb(190, 183, 179)"
borderBottom
:
"1px solid rgb(190, 183, 179)"
borderBottomColor
:
"rgb(190, 183, 179)"
borderBottomLeftRadius
:
"2px"
borderBottomRightRadius
:
"2px"
borderBottomStyle
:
"solid"
borderBottomWidth
:
"1px"
borderColor
:
"rgb(190, 183, 179)"
borderLeft
:
"1px solid rgb(190, 183, 179)"
borderLeftColor
:
"rgb(190, 183, 179)"
borderLeftStyle
:
"solid"
borderLeftWidth
:
"1px"
borderRadius
:
"2px"
borderRight
:
"1px solid rgb(190, 183, 179)"
borderRightColor
:
"rgb(190, 183, 179)"
borderRightStyle
:
"solid"
borderRightWidth
:
"1px"
borderStyle
:
"solid"
borderTop
:
"1px solid rgb(190, 183, 179)"
borderTopColor
:
"rgb(190, 183, 179)"
borderTopLeftRadius
:
"2px"
borderTopRightRadius
:
"2px"
borderTopStyle
:
"solid"
borderTopWidth
:
"1px"
borderWidth
:
"1px"
boxShadow
:
"none"
display
:
"block"
outline
:
"0px"
outlineWidth
:
"0px"
padding
:
"0.6em"
paddingBottom
:
"0.6em"
paddingLeft
:
"0.6em"
paddingRight
:
"0.6em"
paddingTop
:
"0.6em"
width
:
"100%"

รหัส:

function getStyle(className_) {

    var styleSheets = window.document.styleSheets;
    var styleSheetsLength = styleSheets.length;
    for(var i = 0; i < styleSheetsLength; i++){
        var classes = styleSheets[i].rules || styleSheets[i].cssRules;
        if (!classes)
            continue;
        var classesLength = classes.length;
        for (var x = 0; x < classesLength; x++) {
            if (classes[x].selectorText == className_) {
                return _.pickBy(classes[x].style, (v, k) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )
            }
        }
    }

}

อะไรที่ไม่มีการใช้งาน lodash? _.pickBy ไม่มีอยู่จริง
mpag

k & v ถูกย้อนกลับตามสิ่งที่คุณขอจากพวกเขา .... ควรจะกลับมา_.pickBy(classes[x].style, (k,v) => isNaN(parseInt(k)) && typeof(v) == 'string' && v && v != 'initial' && k != 'cssText' )
mpag
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.