我试图突出显示悬停时的一行,这对我来说效果很好。同时,我想在单击时突出显示悬停的行。下面是我到目前为止的代码:
$(".simplehighlight").hover(function() {
$(this).children().css('backgroundColor', '#ffdc87');
},
function() {
$(this).children().css('backgroundColor', '#fff');
});
如果我将点击事件设置为与上面相同,则它不起作用。
$(".simplehighlight").click(function() {
$(this).children().css('backgroundColor', '#ffdc87');
},
function() {
$(this).children().css('backgroundColor', '#fff');
});
关于如何实现这一目标有什么建议吗?
最佳答案
更新:这是一个使用 CSS 类的更好版本:
$(".simplehighlight").click(function() {
$(this).toggleClass('clicked');
// comment the following line if you don't want to dehighlight other rows
$(this).siblings().removeClass('clicked');
});
$(".simplehighlight").hover(function() {
$(this).children().css('backgroundColor', '#ffdc87');
}, function() {
$(this).children().css('backgroundColor', '');
});
CSS 在哪里:
.simplehighlight {
background-color: #fff;
}
.clicked {
background-color: #ffdc87;
}
旧答案: 可以工作,但不必要的复杂。
click
只接受一个回调,而不是两个。您可以使用 data
来检查行是否被单击:
$(".simplehighlight").click(function() {
var clicked = $(this).data('clicked');
$(this).data('clicked', !clicked);
if(clicked) {
$(this).children().css('backgroundColor', '#fff');
}
else {
$(this).children().css('backgroundColor', '#ffdc87');
}
});
然后,为了不更改 mouseleave
上的调用者,请检查 clicked
值:
$(".simplehighlight").hover(function() {
$(this).children().css('backgroundColor', '#ffdc87');
},
function() {
if(!$(this).data('clicked')) {
$(this).children().css('backgroundColor', '#fff');
}
});
关于jquery行悬停和单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4472715/