Permanently change CSS Property with Javascript/D3JS/JQuery

前端 未结 1 1824
小蘑菇
小蘑菇 2021-01-06 13:05

Is there a quick and easy way to \'permanently\' change properties of CSS with Javascript, D3JS, or JQuery? I\'ve found this question which will change geometry already exi

1条回答
  •  一整个雨季
    2021-01-06 13:46

    Magic CSS colour changing fiddle:

    http://fiddle.jshell.net/8xkv3/3/

    The key idea is to access the last stylesheet in the CSS Object Model, and add at the end of that stylesheet a CSS rule specifying the property you want for the selector you want. You want the last rule of the last stylesheet, so that it over-rides anything else in the cascade (except inline styles, of course).

    The stylesheet objects in effect for the document are available as a list at document.styleSheets. Each one has a property cssRules which is a list of rules, which each represent a selector plus a list of property-value pairs.

    The stylesheet.insertRule() method creates a new rule from a string, and adds it to the sheet at the specified index. Unfortunately, it just returns the index, not the rule object, so we have to re-select it to save for future modification.

    You could just repeatedly add on new rules, each over-riding the previous, but that's not very efficient. The rule object has a "style" map with keys and values acting pretty much as you'd predict.

    Edit

    I realized there is a problem with the above approach. What happens if the last stylesheet in the list isn't being used by the current web-page? What if it's a print stylesheet? Or a stylesheet for tiny screenss, or speech synthesizers, or any other media-query limited situation? You could add a rule to that stylesheet object, but it wouldn't have any effect.

    Clearly, what you need to do is create a new stylesheet object with no restrictions and/or with only the restrictions you chose. Then you can add this stylesheet to the end of the list and add your dynamic style rules to it.

    You can't create a stylesheet object directly, but you can create a