2013-10-17 14 views
1

我需要保留点击的div的颜色,直到同一类的另一个div被点击。现在,我有这样的代码:禁用鼠标事件点击为(this)并重新启用它们('.class')。not(this) - jquery

$('.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/

这里唯一的问题是,我不能重新启用以前禁用的事件(以前单击元素)。

这是如何实现的?

回答

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 
    }); 
}); 

FIDDLE

+0

简单,实用,工程进展顺利。谢谢:) – weaponx

+0

@weaponx虽然这回答了关于禁用和启用鼠标输入的orinigal问题,但您尝试使用简单CSS实现的操作会简单得多。 –

0

不要禁用任何东西。只需跟踪以前点击的元素。

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; 
    } 
} 
1

在使用看看this fiddle

你可以完成大部分的工作简单的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'); 
}); 
+0

感谢您的帮助。这有效,但它目前不是我使用的方法,可以在我的小提琴中看到。 – weaponx

+0

我知道我只是告诉你一个“少代码”的方法:) –