【问题标题】:jQuery CSS HoverjQuery CSS 悬停
【发布时间】:2010-12-11 03:42:55
【问题描述】:

我有一个 CSS 菜单,当将鼠标悬停在父 li 上时,它会设置其颜色,它是子 ul(子菜单)。基本上,当您将鼠标悬停在菜单上时,它会改变颜色并保持这种状态,直到您将鼠标悬停在菜单上并且它是子菜单。看起来不错。

我添加了一些 jQuery 代码来更改菜单项的颜色,直到打开某个页面。然后,这些菜单将淡出并恢复颜色。此时,等待悬停改变颜色。

我遇到的问题是,当您使用 jQuery 将颜色更改回其原始状态(在 CSS 中设置)时,它会删除 :hover 类,以防止在将鼠标悬停在其上时颜色发生变化,并且它是子子菜单。有想法该怎么解决这个吗?是否有一个带有 jQ​​uery 的选择器可以让我将 :hover 类恢复正常?

/* ---- Menu Colours ---- */
$(document).ready(function()
{
   var colours = ['d50091', 'c8fa00', '00b4ff', 'b158fc', 'ffa800', '00b72f'];
   var counter = 0; // Loop for the colurs
   var status  = 0; // Status of the colours (greyed out or visible)

   $('ul.menu-horiz').children('li').children('a').hover(function()
   {
      $(this).parent()[0].css('color', '#d50091');
   }, function()
   {
      $(this).parent()[0].css('color', '#b6b6b6');
   });

   $('ul.menu-horiz').children('li').children('a').each(function()
   {
      $(this).css({opacity: 0.2, color: '#' + colours[counter]});
      counter++;
   });

   $('.haccordion .header').click(function()
   {
      if (window.location.hash.substr(1) == 'photogallery')
      {
         $('ul.menu-horiz').children('li').children('a').each(function()
         {
            if ($(this).css('opacity') != '1.1')
            {
               $(this).animate({opacity: 1.1}, 1000).css('color', '#b6b6b6');
            }
         });
      }
      else
      {
         counter = 0;
         if ($('ul.menu-horiz').children('li').children('a').css('opacity') != '0.2')
         {
            $('ul.menu-horiz').children('li').children('a').animate({opacity: 0.2}, 1000, function()
            {
               $('ul.menu-horiz').children('li').children('a').each(function()
               {
                  $(this).css('color', '#' + colours[counter]);
                  counter++;
               });
            });
         }
      }
   });
});

【问题讨论】:

  • 你有$('ul.menu-horiz').children('li').children('a') 三次。您应该将其保存到变量中并获得一些效率。

标签: javascript jquery css hover


【解决方案1】:

您应该能够使用:hover 选择器并传入over()out() 函数,分别设置和取消设置悬停颜色。请参阅:hover documentation 了解更多信息。

简单示例

给定 CSS:

<style>
   .blue { background-color: blue; }
   .red { background-color: red; }
</style>

做这样的事情:

$('li').hover(function() {
      $(this).removeClass('red'); 
      $(this).addClass('blue');
   }, 
   function() {
      $(this).removeClass('blue'); 
      $(this).addClass('red');
   })

【讨论】:

    【解决方案2】:

    当将鼠标悬停在其父级上时,我在将颜色更改应用到时遇到问题

  • (如您在上面发布的代码中所见)。

    直到现在才意识到需要将其更改为

    $('ul.menu-horiz').children('li').hover(function()
    {
       $(this).children('a').css('color', '#d50091');
    }, function()
    {
       $(this).children('a').css('color', '#b6b6b6');
    });
    

    忽略我>_>

  • 【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-23
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 2010-11-06
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多