Tippy Tooltip设置placement:top却显示top-start位置问题求助
问题
我给tippy tooltip设置了placement:top,但点击触发的“Copied!”提示却跑到了top-start位置(怀疑是元素padding搞的鬼)。现在想让这个提示的位置和hover触发的“copy code”tooltip完全对齐,求解决办法。
调用代码
$($copy_button[0]).on("click", (event) => { show_tooltip($copy_button); });
提示函数代码
export function show_tooltip($copy_button) { // 复制成功提示 const instance = tippy($copy_button[0], { placement: 'top', onUntrigger() { remove_instance(); }, }); instance.setContent("Copied!"); instance.show(); function remove_instance() { if (!instance.state.isDestroyed) { instance.destroy(); } } setTimeout(remove_instance, 3000); }
效果对比
- 异常效果:点击后的“Copied!”提示位置偏左(top-start)

- 正常效果:hover时的“copy code”提示居中显示

元素结构示意图

解决办法
大概率是你每次点击都新建tippy实例,和hover的tooltip在目标元素/配置参数上不一致导致的,试试下面几个方案:
1. 复用已有的hover tooltip实例
既然hover的“copy code”提示位置是对的,直接用它来显示“Copied!”就行,不用重新创建实例:
// 获取目标元素上已有的tippy实例 const existingTip = tippy.getInstances($copy_button[0])[0]; if (existingTip) { // 替换内容并显示 existingTip.setContent("Copied!"); existingTip.show(); // 3秒后恢复原提示并隐藏 setTimeout(() => { existingTip.setContent("copy code"); existingTip.hide(); }, 3000); }
2. 对齐新建实例的配置参数
如果必须新建实例,要把定位相关参数和hover实例对齐,比如添加offset、关闭自动调整位置的功能:
export function show_tooltip($copy_button) { const instance = tippy($copy_button[0], { placement: 'top', offset: [0, 10], // 和hover提示的offset保持一致 popperOptions: { modifiers: [ { name: 'flip', options: { enabled: false, // 禁止自动切换位置 }, }, { name: 'preventOverflow', options: { enabled: false, // 禁止溢出调整 }, }, { name: 'computeStyles', options: { padding: 0, // 忽略目标元素的padding影响定位 }, }, ], }, onUntrigger() { remove_instance(); }, }); instance.setContent("Copied!"); instance.show(); function remove_instance() { if (!instance.state.isDestroyed) { instance.destroy(); } } setTimeout(remove_instance, 3000); }
3. 确认目标元素完全一致
检查一下hover的tooltip是不是绑定在父容器上,而点击触发的是子元素——如果目标DOM元素不一样,定位肯定会偏。要保证两者绑定的是同一个元素。
内容的提问来源于stack exchange,提问作者Deekshith Shetty
相关产品推荐
相关产品推荐

