简体   繁体   English

当我将鼠标悬停在父母身上时,如何切换孩子?

[英]How can I toggle a child when I hover over a parent?

Here's some sample HTML 这是一些示例HTML

<style> .icon {display:none;} </style>
<ul>
    <li>ABC <i id="abc" class="icon">x</i></li>
    <li>DEF <i id="def" class="icon">x</i></li>
    <li>GHI <i id="ghi" class="icon">x</i></li>
</ul>

I need to show .icon when I hover over its parent li . 将鼠标悬停在其父li时,需要显示.icon

Here's what I'm trying: 这是我正在尝试的:

$('.icon').each().parent().hover(function() {
    $(this).children('.icon').toggle();
});

Can you point me in the right direction? 你能为我指出正确的方向吗?

There is no need to use each method, you can use $(selector, context) , try the following: 无需使用each方法,可以使用$(selector, context) ,尝试以下方法:

$(document).ready(function() {
   $('ul li').hover(function() {
        $('.icon', this).toggle();
   });
})

You can do this with CSS too (although problematic in IE, since it has issues with :hover on tags other than A): 您也可以使用CSS来做到这一点(尽管在IE中是有问题的,因为它在A以外的标记上存在:hover的问题):

<style> 
.icon {display:none;} 
li:hover .icon {display:inline;}
</style>

I assume you want to show the icon only as long as you hover: 我假设您只想在鼠标悬停时才显示图标:

$('li').hover(

  // called on mouseenter
  function () {
    $(this).find('.icon').show();
  },

  // called on mouseleave
  function () {
    $(this).find('.icon').hide();
  }
);

This method is saver than to simply toggle visibility state in case events get lost.. 与在事件丢失时仅toggle可见性状态相比,此方法更省力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM