-1

假设我有一个类的 3 个 div 元素,悬停其中一个我希望内部元素的背景变为红色。我尝试为每个元素添加一个 ID,如下所示:

<div class="content"><div class="yellow_hover"></div></div>
<div class="content"><div class="yellow_hover"></div></div>
<div class="content"><div class="yellow_hover"></div></div>

jQuery

$('.content').each(function(i, div) {
div.id="div" + (i+1);
});

结果

<div class="content" id="div1"></div>
<div class="content" id="div2"></div>
<div class="content" id="div3"></div>

现在我需要这样的东西,是的,我知道......我迷路了:

$(div+i).hover(function() {
   $('.yellow_hover').css('background-color','#FF9900');
});
4

4 回答 4

3

您不需要 js,在您的 css 中设置以下规则:

.content:hover .yellow_hover {
  background-color: #FF9900;
}

提琴手

于 2014-10-17T09:26:05.883 回答
1

给元素一个像“yellow_box”这样的类

jQuery

$(".yellow_box").hover(
  function() {
    $( this ).addClass( "yellow_hover" );
  }, function() {
   $( this ).removeClass( "yellow_hover" );
 }
); 

当我们悬停一个 div 时,我们添加一个类 (yellow_hover)

有关更多信息,请参阅 jquery 文档 http://api.jquery.com/hover/

于 2014-10-17T09:30:01.593 回答
1

您无需添加id到 div,删除该代码。尝试下面的代码悬停

$('.content').hover(function() {
   $(this).find('.yellow_hover').css('background-color','#FF9900');
}, function(){
   $(this).find('.yellow_hover').css('background-color','#FFFFFF');
});

演示

于 2014-10-17T09:27:20.847 回答
0

在 JS 中你需要这样做:

$('body').on('hover','[id^="div"]',function() {
   $('[id^="div"]').removeAttr( "background-color" );
   $(this).css('background-color','#FF9900');
});
于 2014-10-17T09:29:10.680 回答