JS 阻止或覆盖 CSS 样式
JS blocks or overrides CSS style
我有一个 div,样式是 class。我定义它的样式如下。
.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 遵循的 normal specificity rules 会使您的代码更难理解和维护。
相反,尽可能使用 CSS classes,因为很容易用另一个 class 覆盖 class。当您为 ":hover"
样式完成此操作时,您还可以使用 classList
API 在 JS 中完成此操作,这使得代码更加简单且易于扩展而无需重复代码。
哦,还有 don't use 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>
我有一个 div,样式是 class。我定义它的样式如下。
.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 遵循的 normal specificity rules 会使您的代码更难理解和维护。
相反,尽可能使用 CSS classes,因为很容易用另一个 class 覆盖 class。当您为 ":hover"
样式完成此操作时,您还可以使用 classList
API 在 JS 中完成此操作,这使得代码更加简单且易于扩展而无需重复代码。
哦,还有 don't use 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>