Setting CSS pseudo-class rules from JavaScript

后端 未结 13 1672
爱一瞬间的悲伤
爱一瞬间的悲伤 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 02:03

    One option you could consider is using CSS variables. The idea is that you set the property you want to change to a CSS variable. Then, within your JS, change that variable's value.

    See example below

    function changeColor(newColor) {
      document.documentElement.style.setProperty("--anchor-hover-color", newColor);
      // ^^^^^^^^^^^-- select the root 
    }
    :root {
      --anchor-hover-color: red;
    }
    
    a:hover { 
      color: var(--anchor-hover-color); 
    }
    <a href="#">Hover over me</a>
    
    <button onclick="changeColor('lime')">Change to lime</button>
    <button onclick="changeColor('red')">Change to red</button>

    0 讨论(0)
提交回复
热议问题