一段时间后隐藏工具提示

Hide tooltip after some time

本文关键字:工具提示 隐藏 一段时间      更新时间:2023-09-26

我想要一个效果,当有人在元素上悬停时,他会看到一个工具提示几秒钟,然后工具提示消失,即使鼠标仍在元素上。这就是我所拥有的:

<div data-sentence-tooltip="yes" data-tooltip-content: "some content"> some text </div>
$('[data-sentence-tooltip="yes"]').tooltip({title: function(){return $(this).attr('data-tooltip-content')}});

基于其他相关的SO问题,我尝试了以下两个:

setTimeout(function(){$(".tooltip").fadeOut("fast");}, 2000);

jQuery.fn.delay = function(time,func){
    return this.each(function(){
        setTimeout(func,time);
    });
};
$('[id^="tooltip"]').delay(2000, function(){
    $('[id^="tooltip"]').fadeOut('fast');
    }
);

但我想我知道为什么这些都不起作用。可能是因为.tooltipid=tooltip*被动态添加到DOM中。

参考:

  1. jQuery工具提示,隐藏在..之后。。时间
  2. jquery工具提示设置超时

根据Zoheiry的回答,我终于做到了:

$('[data-sentence-tooltip="yes"]').on('mouseover', function(){
    setTimeout(function(){
    $('#enclosingParentDiv').find('.tooltip').fadeOut('fast');
  }, 1000);
}); 

需要注意的几点:

  1. 我将"mouseover"应用于每个div,因为用户将鼠标悬停在div中的内容上
  2. 我在parent div中搜索.tittip,因为tooltip被添加为同级

添加类似于so 的函数

$('[data-sentence-tooltip="yes"]').on('mouseover', function(){
  // if the tooltip is a child of the element that is being hovered on
  // then write this.
  setTimeout(function(){
    $(this).find('.tooltip').fadeOut();
  }, 2000);
  // if the tooltip is a sibling of the element being hovered on
  // write this
  setTimeout(function(){
    $(this).parent().find('.tooltip').fadeOut();
  }, 2000);
});

这样可以确保您的代码只在悬停在显示该工具提示的项目上后才查找该工具提示。

我通过查看chrome中被检查的元素来了解这一点。不确定这是否完全是万无一失的,是否可以与其他浏览器一起使用

$('input').on('mouseover', function() {
    if(!$(this).is(":focus"))
        $("#" + $(this).attr("aria-describedby")).delay(800).fadeOut(800);
});

if子句是可选的,这使得该代码只有在焦点不在text字段上时才有效。否则,工具提示将继续显示