2013-04-12 130 views
1

我有一个无序的列表作为菜单,悬停效果使用jQuery(不是因为我打算对悬停其他元素进行其他更改)。我对点击应用了效果并禁用了悬停,以防止在鼠标悬停时发生更改,但我似乎无法完成此简单任务。点击效果不会更改背景,因为它已被解除绑定,所以我不能再次单击。jquery悬停更改点击效果

  1. 申请悬停效果
  2. 应用效果可点击项目
  3. 当其他项目被选中

这里删除以前的效果是JS

$(document).ready(function(){ 
//hover 
$('li').hover(function(){ 
    $(this).css('background-color', 'blue'); 
}, function(){ 
    $(this).css('background-color', 'red'); 
}); 

//click 
$('li').click(function(){ 
    $(this).unbind('mouseenter mouseout'); 
    $(this).css('backgrond-color', 'blue'); 
}); 

});

这里是jsfiddle链接。

回答

1

Working Fiddle - 这可以优化,但现在,正如预期

$('li').on('click', function (e) { 
    $('li').each(function() { 
     $(this).css('background-color', 'red'); 
     $('li').hover(function() { 
      $(this).css('background-color', 'blue'); 
     }, function() { 
      $(this).css('background-color', 'red'); 
     }); 
    }); 
    $(this).unbind('mouseenter mouseleave'); 
    $(this).css('background-color', 'blue'); 
}); 
0

使用CSS类和它变得更简单:

$("li").hover(function() { $(this).addClass("hover"); }, function() { $(this).removeClass("hover"); }); 
$("li").click(function() { $("li.selected").removeClass("selected"); $(this).addClass("selected"); }); 

你的CSS:

li { background-color: red; } 
li.selected, li.hover { background-color: blue; } 
1

这工作:

SEE DEMO

$(this).unbind('mouseenter mouseleave'); 

悬停是别名˚F或者mouseenter/mouseleave不是鼠标。

+0

感谢,烤它的工作的。我点击另一个按钮后,如何将mouseenter和mouseleave绑定到上一个按钮? –

1
$('li').click(function() { 
    $('li').not($(this)).bind('mouseenter', function() { 
     $(this).css('background-color', 'blue'); 
    }).bind('mouseleave', function() { 
     $(this).css('background-color', 'red'); 
    }) 
    $(this).unbind('mouseenter mouseleave'); 
    $(this).css('background-color', 'blue'); 
}); 

DEMO HERE

+1

我已经在jsfiddle中改变了这一点,但结果相同。 –

+0

好吧,点击它应该保持蓝色,对吧? –

+0

是的,它应该。并在其他项目被点击时应该重新激活悬停。 –

1

我会使用CSS:悬停选择在样式表

ul { 
    list-style: none; 
    padding: 0; 
} 
ul li { 
    height: 20px; 
    width: 100px; 
    background-color: red; 
    padding: 2px; 
    margin: 2px; 
    text-align: center; 
} 

ul li:hover { 
    background-color: blue; 
} 

然后点击你可以这样做:

$(document).ready(function(){ 

    //click 
    $('li').click(function(){ 
     $('ul li').css('background-color', ''); 
     $(this).css('background-color', 'blue'); 
    }); 
}); 

这里有一个更新的jsfiddle http://jsfiddle.net/SpvUJ/

+0

谢谢RHarrington,这实际上有效。但我试图使用jQuery的悬停,因为我打算将效果应用到列表标记之外的另一个元素。 –

+0

不客气。我试过:) – RHarrington

+0

为什么你的.hover jQuery不适用于这些“其他”元素?您需要在LI元素上使用CSS的唯一原因是由于mouseout事件被触发。李以外的元素不应该是这种情况。 – RHarrington