javascript - 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 属性一样。有什么我想念的吗?
解决方案
虽然评论确实正确地告诉您内联样式是您可以应用的最具体的样式类型,因此最难覆盖,!important
但尽可能避免使用,因为它是对CSS遵循并使您的代码更难理解和维护。
相反,尽可能使用 CSS 类,因为用另一个类覆盖一个类很容易。虽然你已经为你的":hover"
样式做了这些,你也可以在 JS 中使用classList
API来做,这使得代码更加简单和易于扩展,而无需重复代码。
哦,不要使用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>
推荐阅读
- ios - 为什么我的计时器的容差总是减半?
- powershell - 如何将命令链接到远程 PS-Session 并自动化手动输入
- android - android espresso 等待根层次结构获得焦点,第 5 个活动
- django - 无法刷新 JWT 令牌“签名已过期。”
- python - 在列表中查找匹配字符串的“x”示例
- angular - 带查询参数的角度路由
- protocol-buffers - gRPC 中最小的消息大小
- r - 顺序列总和
- web-services - 如何调用安全的 Web 服务
- php - 这个 sql 语句有什么问题,在 series_seasons = '12' 附近产生 mysqli 错误