gpt4 book ai didi

jquery - .addClass() 似乎不起作用

转载 作者:行者123 更新时间:2023-12-01 05:34:19 26 4
gpt4 key购买 nike

在我的第一个项目中,我尝试将 .hover.addClass() 结合起来以突出显示鼠标指针下的 div。

它应该相当简单,但我无法让它工作,这是我到目前为止所写的:

jQuery:

$(document).ready(function() {
$('#NewItem').hover(function() {
$('#NewItem').addClass('active');
});
});

CSS

div {
border-radius: 5px;
transition: background-color 0.5s ease;
}

#NewItem {
border: 1px solid #000000;
background-color: #F0F8FF;
Width: 100px;
height: 50px;
margin-left: auto;
margin-right: auto;
margin-top: 100px;
z-index: 5;
text-align: center;
}

.active {
background-color:#556677;
}

html

<body>
<div id="background">
<div id="NewItem">
<p> Add item </p>
</div>
</div>
</body>

试图找出我出错的地方,我将“.addclass('active')”切换为“.hide()”,它确实使 div 消失了。

最佳答案

它确实在悬停时添加了类。问题在于选择器#NewItem比选择器.active更具体,这意味着背景颜色是用.active选择器添加的正在被覆盖。

specificity #NewItem 的值为 0, 1, 0, 0;而 .active 的特异性为 0, 0, 1, 0。

增加specificity .active 选择器的,并阅读有关 specificity here 的更多信息.

Example Here

#NewItem.active {
background-color: #556677;
}

顺便说一句,如果您打算在 mouseenter 和 mouseout 上切换类,则可能需要使用 .toggleClass() 方法:

Updated Example

$('#NewItem').hover(function() {
$(this).toggleClass('active');
});

或者完全避免使用 jQuery 并使用 :hover 伪类(如果适用于您的情况):

Updated Example

#NewItem:hover {
background-color: #556677;
}

关于jquery - .addClass() 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34970166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com