Get CSS not-computed property-value with Javascript only [duplicate]

萝らか妹 提交于 2021-02-15 07:11:41

问题


Because I am quite new to programming and I am discovering Bootstrap right now, I am doing an exercise with containers and rows and col-XX etc., to know how what are their CSS properties.

Therefore, I am looking for getting the CSS values that devs put in the CSS files with Javascript. Not jQuery, but vanilla JS. Not the CSS values computed, but the CSS values written. Like the one we have in the console. I want to get them in order to put them back in a the HTML this way : <p>margin-right: 5%</p>, for example.

So a lot of people are talking about window.getComputed(element).getPropertyValue("property"), but I am not interested. I heard somewhere cssText, but I am not sure that it's the good one.

Is there a solution ? Is there actually a place somewhere where all the property-values-written of a selector are stored, in parallel to the property-values-computed ?

Thanks Arnaud

PS: I know the subject is already open there but it opened 7 years ago, and the only self-answer is not satisfying I think...


回答1:


If you need to access this information programmatically (as opposed to just looking at it in devtools), you're looking for the document.styleSheets collection. Each stylesheet in the collection has the CSS rules and media query rules, etc., for that stylesheet, in a form where you can access the actual style info, not the computed result.

For example:

var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
forEach(document.styleSheets, function(sheet, index) {
  forEach(sheet.cssRules || sheet.rules, function(rule) {
    if (rule instanceof CSSStyleRule && rule.selectorText == ".foo") {
      console.log(".foo's width rule: " + rule.style.width);
    }
  });
});
.foo {
  width: calc(100% - 10px);
}


来源:https://stackoverflow.com/questions/46828223/get-css-not-computed-property-value-with-javascript-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!