2010-06-03 311 views
1

jQuery代码:jQuery的鼠标悬停改变背景颜色

$(".menu_clickable").mouseover(function() { 
    $(this).css({'background-color' : '#F00'}).mouseout(function(){ 
     $(this).css({'background-color' : '#FFF'}); 
    }); 
}); 


$(".menu_clickable").live('click', function() { 
    $(this).css({'background-color' : '#FCC'}); 
}); 

HTML源代码:

<div class="menu_clickable prof_info2" id="prof_info" >first</div> 
<div class="menu_clickable prof_info3" id="prof_info" >second</div> 
<div class="menu_clickable prof_info3" id="prof_info" >third</div> 

我试图使用jQuery做悬停效应和它工作正常,但如果我想改变DIV背景颜色当它被点击时它不起作用,实际上点击的DIV会改变背景颜色,但当光标放在它上面时它会保持原样。如果将其移出,它将恢复原始背景颜色。为什么?

回答

3
  1. 您正在附加太多的mouseout处理程序。每次将鼠标移动到menu_clickable上方时,您都会更改bacgkround,然后再附加其他鼠标事件。那很糟。

  2. 您正在使用正常程序附加单击事件“live”和鼠标*。为什么?基本上如果你需要现场附加使用它,否则更好保持清晰(更好的性能)。

  3. 使用css类更改UI要容易得多。像

CSS

.menu_clickable { background-color: #FFF; /* default color */ } 
.clicked { background-color: #FCC; /* color for clicked button */ } 
.mouseover { background-color: #F00; /* color when hovered */ } 

HTML

<div class="menu_clickable prof_info2" id="prof_info">first</div> 
<div class="menu_clickable prof_info3" id="prof_info">second</div> 
<div class="menu_clickable prof_info3" id="prof_info">third</div> 

jQuery的

$(document).ready(function() { 
    $(".menu_clickable") 
     .mouseover(function() { 
      var t = $(this); 
      if (!t.hasClass("clicked")) { // very easy to check if element has a set of styles 
       t.addClass('mouseover'); 
      } 
     }) 
     .mouseout(function() { // attach event here instead of inside mouse over 
      $(this).removeClass('mouseover'); 
     }); 

    $(".menu_clickable").click(function() { 
     var t = $(this); 
     t.toggleClass("clicked"); 
     if (t.hasClass("clicked")) { 
      t.removeClass('mouseover'); 
     } else { 
      t.addClass('mouseover'); 
     } 
    }); 
}); 

这将有悬停效果,如果按钮没有被点击;点击后它会保持#FCC直到再次点击。

0

因为鼠标点击事件在点击后再次改变颜色。

+0

如何停止clicked DIV上的鼠标悬停事件? – Sergio 2010-06-03 19:13:08

+0

@Sergio - 您只需删除与其关联的功能,或者在鼠标点击DIV时使用不同的类/功能 – Sairam 2010-06-03 19:16:50

4

首先,您确实没有正确使用mouseout。你的方式,每当mouseover元素,你的分配mouseout事件处理程序。

其次,您可能想要告诉mouseout如果点击了它,不会更改背景。为了这个目的,类可以很方便。它应该是这样的。

活生生的例子:http://jsfiddle.net/qNmZe/

$(".menu_clickable").mouseover(function() { 
    $(this).css({'background-color' : '#F00'}); 
}); 

$(".menu_clickable").mouseout(function(){ 
    if(!$(this).hasClass('clicked')) 
     $(this).css({'background-color' : '#FFF'}); 
}); 


$(".menu_clickable").live('click', function() { 
    $(this).css({'background-color' : '#FCC'}) 
      .addClass('clicked'); 
}); 

编辑:事实上,因为你分配一个clicked类的元素,你可以只使用你的风格,而不是直接应用background-color 。尽管如此。