首页 > 解决方案 > JS 阻止或覆盖 CSS 样式

问题描述

我有一个带有样式类的 div。我定义它的风格如下。

.widgetContainer:hover{
    border-radius: 0rem;
    top: 0rem;
    left: 0rem;
    height: 100%;
    width: 100%;
}

在 JS 中,我为点击事件定义了一个方法。

exitWidget(event){
        if(event.target === document.getElementsByClassName("widgetContainer")[0])
        {
            document.getElementsByClassName("widgetContainer")[0].style.height = "3rem";
            document.getElementsByClassName("widgetContainer")[0].style.width = "3rem";
        }
    }

CSS 样式和事件符合预期。问题是当我在事件发生后再次悬停 div 时。属性高度和宽度不会增长以填满屏幕。就像 JS 覆盖了 CSS 属性一样。有什么我想念的吗?

标签: javascripthtmlcssonclickhover

解决方案


虽然评论确实正确地告诉您内联样式是您可以应用的最具体的样式类型,因此最难覆盖,!important但尽可能避免使用,因为它是对CSS遵循并使您的代码更难理解和维护。

相反,尽可能使用 CSS 类,因为用另一个类覆盖一个类很容易。虽然你已经为你的":hover"样式做了这些,你也可以在 JS 中使用classListAPI来做,这使得代码更加简单和易于扩展,而无需重复代码。

哦,不要使用getElementsByClassName().

// Just get your static element references just once, not every time
// the function runs and don't use getElementsByClassName().
const widget = document.querySelector(".widgetContainer");

widget.addEventListener("mouseout", exitWidget);

function exitWidget(event){
 if(event.target === widget){
     widget.classList.add("otherClass"); // <-- How simple is that?!
 }
}
.widgetContainer:hover{
    border-radius: 0rem;
    top: 0rem;
    left: 0rem;
    height: 100%;
    width: 100%;
    background:yellow;
}

.otherClass {
  height:3rem;
  width:3rem;
}
<div class="widgetContainer">This is the widget container</div>


推荐阅读