【问题标题】:change css for parent div when hover on link [duplicate]将鼠标悬停在链接上时更改父 div 的 css [重复]
【发布时间】:2021-06-22 02:16:35
【问题描述】:

我尝试了这个解决方案,但遗漏了一些东西:change background of parent div on hover

这是我的html:

<div class="box">
    <h3 class="page-header item-title">                                              
          <a class="titlelink" href="/index.php?option=com_content&amp;view=category&amp;id=11&amp;Itemid=234">
                Modeling</a>

这是我尝试在此处覆盖的内容:/templates/shaper_helixultimate/html/com_content/category/default_children.php

$document = JFactory::getDocument();
$document->addScriptDeclaration('
$('.box > .titlelink').hover(function(){
$(this).parent().toggleClass('hover');
})
    });
');

http://jsfiddle.net/t5hf8qdc/

我做错了什么?

$('.box > .titlelink').hover(function() {
  $(this).parent().toggleClass('hover');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
  <h3 class="page-header item-title">
    <a class="titlelink" href="/index.php?option=com_content&amp;view=category&amp;id=11&amp;Itemid=234">
                    Modeling</a>
  </h3>
</div>

【问题讨论】:

  • 为什么不简单地使用css? .box a.titlelink:hover{ /* your hover css */ }
  • @Kinglish,没有带有 CSS 的父选择器。

标签: javascript joomla hover


【解决方案1】:

选择器.box &gt; .titlelink 查找父子关系。你没有那个。

请改用.box .titlelink

$('.box .titlelink').hover(function() {
  $(this).parent().toggleClass('hover');
});
.hover {
  background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
  <h3 class="page-header item-title">
    <a class="titlelink" href="/index.php?option=com_content&amp;view=category&amp;id=11&amp;Itemid=234">
                    Modeling</a>
  </h3>
</div>

【讨论】:

    【解决方案2】:

    正如@isherwood 提到的,您链接到的解决方案使用的结构与您所拥有的不同。 CSS 选择器中的&gt; 指定您的目标是直接子代,而在两个选择器之间留一个空格来查找任何后代

    .box > .titlelink {
      /* targets where .titlelink is a child of .box */
    }
    
    .box .titlelink {
      /* targets where .titlelink is a descendant of .box */
    }
    

    如果您想像您引用的解决方案那样使用严格的 CSS 选择器,您可以这样做:

    $('.box > .item-title > .titlelink').hover(function(){
      $(this).parent().toggleClass('hover');
    });
    

    虽然这会将hover 类添加到.item-title 元素,而不是.box 元素。假设您特别希望针对您正在侦听的 hover 事件的 .box 祖先,那么您想要:

    $('.box > .item-title > .titlelink').hover(function(){
      $(this).parents('.box').toggleClass('hover');
    });
    

    因为 jQuery 的 parents 方法允许您传递选择器来定位特定的祖先,在树中向上移动多个级别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 2020-08-07
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多