如何在hover子元素时隐藏父元素的:before伪元素内容?
解决方案:隐藏含子菜单的父元素:hover伪元素
这里有两种可行的方案,你可以根据项目的浏览器兼容性需求来选择:
方案一:使用CSS :has()选择器(现代浏览器推荐)
这种方式不需要修改HTML,直接通过CSS就能精准匹配包含子菜单的父元素。你只需要在现有的CSS基础上,添加一个针对包含.childrens子元素的.menu-items的hover规则:
/* 保留你原来的伪元素样式,顺便修正visibility的错误写法 */ .menu-items:hover::before { content: attr(data-title); position: absolute; bottom: -80px; display: inline-block; padding: 0px 6px; border-radius: 2px; background: #fff; color: gray; font-size: 11px; font-family: sans-serif; white-space: nowrap; z-index: 999; height: 30px; min-width: 100px; left: 17px; text-align: center; line-height: 30px; font-weight: bold; border: 1px solid gray; visibility: visible; /* 如果需要过渡动画,可以加上下面的规则 */ opacity: 1; transition: visibility 0s, opacity 0.3s ease-in-out; } /* 当menu-items包含childrens子元素时,hover隐藏伪元素 */ .menu-items:has(.childrens):hover::before { visibility: hidden; opacity: 0; transition: visibility 0.3s ease-in-out, opacity 0.3s ease-in-out; }
说明
:has()是CSS的父选择器,它可以匹配包含指定子元素的父元素。这里.menu-items:has(.childrens)会选中所有包含.childrens类子元素的菜单项,当鼠标hover时,我们通过visibility: hidden和opacity: 0来隐藏伪元素(配合过渡动画会更平滑)。
注意::has()目前支持Chrome、Edge、Safari 15.4+以及Firefox 121+(需开启layout.css.has-selector.enabled),如果你的项目需要兼容旧版浏览器,可以看下面的方案。
方案二:通过Angular动态添加类(兼容旧浏览器)
这种方式需要修改HTML,给有子菜单的菜单项额外添加一个类,然后通过CSS控制伪元素的显示:
第一步:修改HTML的<li>标签
在*ngFor中判断当前菜单是否有子元素,如果有就添加has-children类:
<li *ngFor="let menu of menus" class="{{ menu.attributes.class }} menu-items {{ menu.children && menu.children.length ? 'has-children' : '' }}" [attr.data-title]="menu.label"> <a [routerLink]="[menu.url||'/']" [queryParams]="menu.refParameter3 ? menu.refParameter3:{}" (click)="clicked = true;selectMenu(menu)"> <i *ngIf="menu.icon" class="{{menu.icon}}"></i> <span>{{menu.label}}</span> <i *ngIf="menu.children && menu.children.length" class="subarrow fa fa-angle-right"></i> </a> <z-menu class="childrens" *ngIf="menu.children && menu.children.length" [menus]="menu.children" [parent]="menu.label"></z-menu> </li>
第二步:修改CSS
添加针对has-children类的hover规则:
/* 保留你原来的伪元素样式 */ .menu-items:hover::before { content: attr(data-title); position: absolute; bottom: -80px; display: inline-block; padding: 0px 6px; border-radius: 2px; background: #fff; color: gray; font-size: 11px; font-family: sans-serif; white-space: nowrap; z-index: 999; height: 30px; min-width: 100px; left: 17px; text-align: center; line-height: 30px; font-weight: bold; border: 1px solid gray; visibility: visible; opacity: 1; transition: visibility 0s, opacity 0.3s ease-in-out; } /* 有子菜单的项hover时隐藏伪元素 */ .menu-items.has-children:hover::before { visibility: hidden; opacity: 0; transition: visibility 0.3s ease-in-out, opacity 0.3s ease-in-out; }
说明
这种方式兼容性更好,所有支持CSS的浏览器都能生效,因为它只是通过静态类名来控制样式,不需要依赖新的CSS选择器。
内容的提问来源于stack exchange,提问作者None
相关产品推荐
相关产品推荐

