You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular技术问题:悬停文本显示容器,悬停容器时容器消失

解决悬停文本显示容器、悬停容器时不消失的问题

为啥当前代码不行?

当你把鼠标从<p>移到<div>容器时,会先触发<p>的mouseleave事件,直接把displayProp改成false,容器瞬间就被销毁了,根本来不及触发容器的mouseenter,所以容器会消失。

方案一:用父容器统一管理悬停

把文本和容器包在同一个父<div>里,只监听父容器的鼠标进出事件。这样只要鼠标在父容器范围内(不管是在文本还是容器上),容器都能保持显示。

修改后的HTML代码

<div (mouseenter)="displayPrope()" (mouseleave)="hidePrope()">
  <p>show on hover</p>
  <div *ngIf="displayProp" class="prop-div">
    <span style="color: white">i am the container</span>
  </div>
</div>

TS代码无需修改

displayProp: boolean = false;

displayPrope() {
  this.displayProp = true;
}

hidePrope() {
  this.displayProp = false;
}

方案二:添加延迟隐藏定时器

如果不想调整DOM结构,可以在隐藏方法里加个定时器,延迟几百毫秒再隐藏容器,给鼠标留够移到容器上的时间。同时在显示方法里清除之前的定时器,避免已经移到容器上了还触发隐藏。

修改后的TS代码

displayProp: boolean = false;
hideTimer: any;

displayPrope() {
  clearTimeout(this.hideTimer); // 清除之前的隐藏定时器
  this.displayProp = true;
}

hidePrope() {
  // 延迟300ms隐藏,时长可根据需求调整
  this.hideTimer = setTimeout(() => {
    this.displayProp = false;
  }, 300);
}

HTML代码无需修改

<p (mouseenter)="displayPrope()" (mouseleave)="hidePrope()">show on hover</p>
<div
  *ngIf="displayProp"
  (mouseenter)="displayPrope()"
  (mouseleave)="hidePrope()"
  class="prop-div"
>
  <span style="color: white">i am the container</span>
</div>

内容的提问来源于stack exchange,提问作者manjiro sano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:05:24