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

Tippy.js动态tooltip问题:无法销毁旧提示导致重复显示

解决Tippy tooltip点击切换时重复创建的问题

你的问题核心在于每次点击都销毁旧实例再重建新实例,不仅效率低,还可能因为实例管理不当导致残留的tooltip DOM元素。正确的做法是初始化一次实例,点击时直接更新内容。

修正后的代码

HTML(保持不变)

<button>Button</button>

<div id="1" style="display:none"><span>Some text here</span><br><span>and here</span></div>
<div id="2" style="display:none"><span>Over</span><br></div>

JavaScript

// 初始化内容索引,从第一个内容开始
let idIndex = 1;
// 获取按钮元素并初始化一次tippy实例,保存引用
const button = document.querySelector('button');
const tippyInstance = tippy(button, {
  allowHTML: true,
  animation: 'shift-away',
  interactive: true,
  content: document.getElementById(idIndex).innerHTML,
  maxWidth: 600,
});

// 点击按钮时直接更新tooltip内容
button.addEventListener('click', () => {
  // 切换索引,在1和2之间循环
  idIndex = idIndex === 1 ? 2 : 1;
  // 使用实例的setContent方法更新内容
  tippyInstance.setContent(document.getElementById(idIndex).innerHTML);
});

为什么原代码会出问题?

  1. 第一次点击时的无效销毁:初始状态下按钮还没有tippy实例,执行tippy('button')[0].destroy()时,tippy会先为按钮创建一个临时实例再销毁,之后又创建新实例——这一步完全多余,还可能留下DOM残留。
  2. 重复创建实例的风险:每次调用tippy()都会尝试为元素创建新实例,即使销毁了旧实例,也可能因为DOM清理不及时导致新旧tooltip同时显示。

关键优化点

  • 提前初始化tippy实例并保存引用,避免重复调用tippy()创建实例。
  • 使用Tippy内置的setContent()方法直接更新内容,这是官方推荐的动态修改内容的方式,无需销毁重建。
  • 增加索引循环逻辑,避免索引超出范围导致找不到内容元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:27:38