【问题标题】:Hovering issue with JqueryJquery的悬停问题
【发布时间】:2014-10-17 09:24:23
【问题描述】:

假设我有一个类的 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');
});

【问题讨论】:

  • 真的是这样吗? .yellow_hover DIV 消失了吗?

标签: jquery progressive


【解决方案1】:

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

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

JsFiddle

【讨论】:

  • 这个 CSS 会改变两个 div 的背景颜色。内容 div 内部是一个小区域(yellow_hover div)。悬停较大的 div 必须改变 Yellow_hover 的颜色。
  • 你说得对,对不起,我看到了“.content: hover .yellow: hover”,工作了好几个小时......
【解决方案2】:

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

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

DEMO

【讨论】:

  • 你不喜欢通过 css 做这个吗?
  • 这么简单?就这样。谢谢
  • 是的,这很简单..第一个悬停功能和第二个悬停功能
  • @PatsyIssa,是的,CSS3 也是操作 DOM 或动画的选项之一。
【解决方案3】:

给元素一个类似“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/

【讨论】:

    【解决方案4】:

    在 JS 中你需要这样做:

    $('body').on('hover','[id^="div"]',function() {
       $('[id^="div"]').removeAttr( "background-color" );
       $(this).css('background-color','#FF9900');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多