Setting CSS pseudo-class rules from JavaScript

后端 未结 13 1653
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:01

I\'m looking for a way to change the CSS rules for pseudo-class selectors (such as :link, :hover, etc.) from JavaScript.

So an analogue of the CSS code: a:hove

13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 01:54

    Just place the css in a template string.

    const cssTemplateString = `.foo:[psuedoSelector]{prop: value}`;
    

    Then create a style element and place the string in the style tag and attach it to the document.

    const styleTag = document.createElement("style");
    styleTag.innerHTML = cssTemplateString;
    document.head.insertAdjacentElement('beforeend', styleTag);
    

    Specificity will take care of the rest. Then you can remove and add style tags dynamically. This is a simple alternative to libraries and messing with the stylesheet array in the DOM. Happy Coding!

提交回复
热议问题