1

I need to keep the color of the clicked div until another div of the same class gets clicked. Right now I have this code:

$('.aaa').mouseenter(function () {
    $(this).css('background', '#dddddd');
});
$('.aaa').mouseleave(function () {
    $(this).css('background', '#888888');
});
$('.aaa').click(function () {
    $(this).css('background', '#555555');
    $('.aaa').not(this).css('background', '#111111');
    $(this).off('mouseenter mouseleave');
    $('.aaa').not(this).on('mouseenter mouseleave');
});

http://jsfiddle.net/5jUP7/

Only problem here is that I can't re-enable previously disabled events (for previously clicked elements).

How can this be achieved?

4

3 回答 3

1

将您的处理程序放在函数中,以便在多个地方轻松引用它们。

$(".aaa").on({
    mouseenter: mouseEnter,
    mouseleave: mouseLeave
});

function mouseEnter() {
    $(this).css('background', '#dddddd');
}
function mouseLeave() {
    $(this).css('background', '#888888');
}
$(".aaa").click(function() {
    $(this).css('background', '#555555');
    $(".aaa").not(this).css('background', '#111111');
    $(this).off('mouseenter mouseleave');
    $(".aaa").not(this).on({
        mouseenter: mouseEnter,
        mouseleave: mouseLeave
    });
});

小提琴

于 2013-10-17T16:29:32.220 回答
1

看看这个小提琴

您可以使用简单的 CSS 完成大部分工作

HTML

<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>
<div class="aaa"></div>

CSS

.aaa {
    display:block;
    background:#888;
    width: 300px;
    height: 30px;
    border: 1px solid #000;
}
.aaa:hover,
.aaa.disabled:hover{
    display:block;
    background:#ddd;
}
.aaa.active {
    background:#111;
}
.aaa.disabled {
    background:#555;
}

JAVASCRIPT

$('.aaa').click(function () {
    $('.aaa').removeClass('active disabled');
    $(this).addClass('active');
    $('.aaa').not($(this)).addClass('disabled');
});
于 2013-10-17T16:34:37.923 回答
0

Don't disable anything. Just keep track of the previously clicked element.

var lastObjClicked;
function clicked(this){
  var thisClass = this.className;

  if( lastObjClicked.className == thisClass){
    document.getElementById(lastObjClicked.id).style.color = '#FF0000';
    document.getElementById(this.id).style.color = '#FF0000';

  }else{
    lastObjClicked = this;
  }
}
于 2013-10-17T16:29:14.547 回答