我有几个<p class="first">
我使用 css 的 s :hover
在悬停时更改背景色:
<div id="row_1">
<p class="first">first_1</p>
<p class="first">first_2</p>
<p class="first">first_3</p>
<p class="first">first_4</p>
<p class="first">first_5</p>
</div>
和CSS:
.first:hover {
background-color: #ddd;
}
但我正在做的也是发射 .click()
每次.first
被点击,将被点击的设置为不同的背景,将其他设置为蓝色:
$('.first').click(function() {
$(this).css('background-color', '#ddd');
$('.first').not(this).css('background-color', 'blue');
});
令我感到困惑的是,在 jQuery 函数触发 :hover
之后不再工作了?
有人知道为什么吗?是否:hover
改了bg就不能用了?
最佳答案
使用 .css('background-color','blue')
会将元素上的 style
属性设置为 background-color:blue ;
这比 css 悬停样式更具体。这就是为什么您不再看到悬停时背景颜色发生变化的原因。
解决方法是像这样为 css 样式使用类名
.blueBg {
background-color: blue;
}
.greyBg{
background-color: #ddd;
}
然后点击添加和删除这些类名
$('.first').click(function() {
$('.blueBg').removeClass('blueBg');
$(this).addClass('greyBg');
$('.first').not(this).addClass('blueBg');
});
关于jquery - CSS :hover does not work after jQuery css change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22919257/