直接更改 CSS 样式表

时间:2021-08-01 16:30:09

标签: javascript html css

我这里有一个独特的情况。我在 HTML 中有几个按钮: Buttons 通常它们看起来像左边的那个,但是当我将鼠标悬停在它们上面时,它们会产生动画并且看起来像右边的。

我还添加了两个颜色选择器,分别改变背景和前景。 (两个选择器都会影响整个文档以及按钮)

// Background color changer
var allb = document.getElementsByClassName('button');
for (var i = 0; i < allb.length; i++) {
  allb[i].style.backgroundColor = bgcolor;
}

// Foreground color changer
var allf = document.getElementsByClassName('button');
for (var i = 0; i < allf.length; i++) {
  allf[i].style.color = focolor;
  allf[i].style.borderColor = focolor;
}

如果我同时使用两个颜色选择器,那么当我将鼠标悬停在按钮上时,动画会中断并且没有任何变化。我明白为什么 - 颜色选择器对样式有持久的影响。

有没有办法直接改变CSS文件,或者绕过这个问题?

我的代码

.button {
    font-family: SF, Arial, Helvetica, sans-serif;
    background-color: #4c56af;
    border: none;
    padding: 16px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 30px;
    margin: 4px 2px;
    transition-duration: 0.4s;
    cursor: pointer;
}
  
.button1 {
    border-radius: 10px;
    font-family: SF, Arial, Helvetica, sans-serif;
    background-color: rgba(255, 255, 255, 0);
    color: black;
    border: 4px solid #4c56af;
}
  
.button1:hover {
    border-radius: 10px;
    font-family: SF, Arial, Helvetica, sans-serif;
    background-color: #4c56af;
    color: white;
}

每个按钮大致如下所示:

<button type="button" onclick=func() class="button button1">Play</button>

2 个答案:

答案 0 :(得分:1)

您可以修改样式表中包含的规则列表。您可以通过 StyleSheetListCSSStyleSheet 接口做到这一点。

选择有问题的样式表:

const styleSheet = document.styleSheets[0] // Use the index for the stylesheet whose rules you want to modify

使用 insertRule() method 插入规则:

const bgcolor = "green";
const focolor = "yellow";

styleSheet.insertRule(`
   button {
      background-color: ${bgcolor};
      color: ${focolor};
      border-color: ${focolor};
   }
`, styleSheet.cssRules.length);

styleSheet.insertRule(`
   button:hover {
      background-color: ${focolor};
      color: ${bgcolor};
   }
`, styleSheet.cssRules.length);

如果需要,您可以在之后通过 deleteRule() method 删除这些规则。

答案 1 :(得分:1)

这是一种解决方法。 将您的 CSS 动画代码编写为一个单独的类,如下所示:

.button--animated {
    border-radius: 10px;
    font-family: SF, Arial, Helvetica, sans-serif;
    background-color: #4c56af;
    color: white !important;
}

然后在所有按钮元素上使用mouseenter 事件向其添加过渡类,并使用 'mouseleave' 将其移除:

buttonElement.addEventListener("mouseenter", function() {
    element.classList.add('button--animated')
});
buttonElement.addEventListener("mouseleave", function() {
    element.classList.remove('button--animated')
});

如果它不起作用,请将 !important 添加到 button--animated 类的 CSS。这并不理想,但可以完成工作。