monyinet

Editar estilo CSS

Oct 23rd, 2020 (edited)
608
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function adjustCSSRules(selector, props, sheets){
  2.    
  3.     // get stylesheet(s)
  4.     if (!sheets) sheets = [...document.styleSheets];
  5.     else if (sheets.sup){    // sheets is a string
  6.         let absoluteURL = new URL(sheet, document.baseURI).href;
  7.         sheets = [...document.styleSheets].filter(i => i.href == absoluteURL);
  8.         }
  9.     else sheets = [sheets];  // sheets is a stylesheet
  10.        
  11.     // CSS (& HTML) reduce spaces to one. TODO: ignore quoted spaces.
  12.     selector = selector.replace(/\s+/g, ' ');
  13.     const findRule = s => [...s.cssRules].reverse().find(i => i.selectorText == selector)
  14.     let rule = sheets.map(findRule).filter(i=>i).pop()
  15.  
  16.     const propsArr = props.sup
  17.         ? props.split(/\s*;\s*/).map(i => i.split(/\s*:\s*/)) // from string
  18.         : Object.entries(props);                              // from Object
  19.            
  20.     if (rule) for (let [prop, val] of propsArr)
  21.         rule.style[prop] = val;
  22.     else {
  23.         sheet = sheets.pop();
  24.         if (!props.sup) props = propsArr.reduce((str, [k, v]) => `${str}; ${k}: ${v}`, '');
  25.         sheet.insertRule(`${selector} { ${props} }`, sheet.cssRules.length);
  26.         }
  27.     }
  28.    
  29. var s = document.styleSheets[1];
  30. adjustCSSRules("body", 'background-color: green');
  31. adjustCSSRules("body", {"background-color": "purple"});
  32. adjustCSSRules("p", {border: '2px solid blue'}, s);
  33. adjustCSSRules("div", {color: 'yellow'}, s);
  34. adjustCSSRules("div", 'color:red; border: 3px solid blue;');
  35. console.log(s);
  36.  
RAW Paste Data