我有一些<p class="first">s,我使用css :hover来改变悬停时的bg颜色:
<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>
Run Code Online (Sandbox Code Playgroud)
和css:
.first:hover {
background-color: #ddd;
}
Run Code Online (Sandbox Code Playgroud)
但我正在做的事情就是.click()每次.first点击都会点火,这会点击一个不同的bg,其他的则是蓝色的:
$('.first').click(function() {
$(this).css('background-color', '#ddd');
$('.first').not(this).css('background-color', 'blue');
});
Run Code Online (Sandbox Code Playgroud)
令我困惑的是,在jQuery函数启动后,:hover它不再起作用了吗?
有谁知道为什么?是否:hoverBG为更改后不再工作?
使用.css('background-color','blue')将style在元素上设置background-color:blue;比css悬停样式更具体的属性.这就是为什么你不再看到悬停时背景颜色的变化.
解决方法是使用类名称作为css样式
.blueBg {
background-color: blue;
}
.greyBg{
background-color: #ddd;
}
Run Code Online (Sandbox Code Playgroud)
然后在点击时添加和删除这些类名
$('.first').click(function() {
$('.blueBg').removeClass('blueBg');
$(this).addClass('greyBg');
$('.first').not(this).addClass('blueBg');
});
Run Code Online (Sandbox Code Playgroud)