【问题标题】:Changing A Different Class Display on Hover with Jquery使用 Jquery 在悬停时更改不同的类显示
【发布时间】:2010-04-25 03:12:32
【问题描述】:

好的,这就是我想要做的。我有一个 DIV 框,其子元素设置为 DISPLAY: NONE;。我正在尝试使用 Jquery,以便当鼠标进入父 DIV 框时,子元素可见,然后在鼠标离开父 DV 时隐藏。这些类的页面上会有多个 div。由于某种原因,它不起作用。有任何想法吗?这是我的代码:

HTML:

<div class="parent">  
     <span class="handle" style="display: none;">My Handle</span>
     <p>Child Text</p>
</div>

Javascript:

$(document).ready(function () {
    $('.parent').mouseenter(function(){
        $(this).next('.handle').show();
    });
    $('.parent').mouseleave(function(){
        $(this).next('.handle').hide();
    });
})

【问题讨论】:

  • 您是否考虑过下面的纯 CSS 解决方案?

标签: jquery css-selectors traversal


【解决方案1】:

改用find:

$(document).ready(function () {
    $('.parent').mouseenter(function(){
        $(this).find('.handle').show();
    });
    $('.parent').mouseleave(function(){
        $(this).find('.handle').hide();
    });
})

或者更好,试试这个:

$(document).ready(function () {
    $('.parent').hover(function(){
        $('.handle', this).show();
    },
    function(){
        $('.handle', this).hide();
     });
   );
})

【讨论】:

  • 我建议指定元素类型。它加快了查询速度。
  • @ChaosPandion:OP 可能想要将元素从 span 更改为其他元素。尽可能保持通用性,以避免将来出现问题。
【解决方案2】:

不用 jQuery 也能实现你的目标:

 .parent .handle{  
    display:none;  
 }  
 .parent:hover .handle{
    display:inline;
 }

<div class="parent">  
   <span class="handle">My Handle</span>
   <p>Child Text</p>  
</div>

您应该只使用 CSS,因为它消除了对 Javascript 的需求。

经过测试的 FF 和 Safari

【讨论】:

  • 这行不通。一旦元素被隐藏,我就无法检测到它。 仅在 Firefox 中测试。
  • 最后,我使用 jQuery 的目的不仅仅是更改显示,但这是解决我提出的问题的好方法。谢谢!
【解决方案3】:

我建议您使用hover。这意味着您只需要运行一次查询。

$('div.parent').hover(
    function () {
        $(this).children('span.handle').show();
    },
    function () {
        $(this).children('span.handle').hide();
    }
);

【讨论】:

    【解决方案4】:

    试试这个吧:

    $(document).ready(function () {
        $('.parent').mouseenter(function(){
            $(this).next('.handle').show();
        }).mouseleave(function(){
            $(this).next('.handle').hide();
        });
    })
    

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-10
      相关资源
      最近更新 更多