Cascading <li>-hover effect using CSS [duplicate]

左心房为你撑大大i 提交于 2019-12-05 04:51:11

This solution isn't a purely HTML/CSS one, but it works. It uses the Javascript library jQuery.
http://jsfiddle.net/XP3Vp/

Put this in the head-section of your page:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$('li').mouseover(function()
  {
          if ($('li ul li:hover').length) 
          {
              $('li ul li:hover').css('background','red'); 
          }
          else
          {
               $('li:hover').css('background','red'); 
          }
  });
$('li').mouseout(function()
  {
          $(this).css('background', 'transparent');
  });
</script>

Use this if you don't want the underlying list items to be highlighted as well when moving the cursor over Group 1: http://jsfiddle.net/CwhhN/

The best you can do is to colorize the ul as well ..

ul{background-color:#fff;}
li:hover
{
    background-color:#ff0000;
}

something like this http://jsfiddle.net/gaby/DxsDa/ although it will still highlight the group 1 text..


Alternatively you can resort to invalid html but i would not suggest that for obvious reasons.. http://jsfiddle.net/gaby/DxsDa/1/

ANeves

Group 1 contains Item 2. So, when you are hovering Item 2 you are also hovering Group 1.

Thus, with CSS what you want is not possible without mis-formatting HTML on purpose.

With JS you can get there, though.
If this is acceptable, refer to @RobinJ's answer.

Found probably the best solution at the jQuery documentation. http://api.jquery.com/event.stopPropagation/

$('li').mouseover(function(e)
{
    e.stopPropagation();
    $(this).addClass('hover');
});

$('li').mouseout(function()
{
    $(this).removeClass('hover');
});

Use class or id for UL element (which is parent for highlighted li's) and directly children selector:

ul#your_id > li:hover{ background-color: #f00; }

It will fix error which happens because you try to highlight every li's elements :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!