一段时间后隐藏工具提示

3

我希望当有人悬停在一个元素上时,能够出现一个提示框,并持续几秒钟后消失,即使鼠标仍停留在该元素上。以下是我的代码:

<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提示工具设置超时

你的JavaScript/jQuery代码是在任何监听器内部还是在页面运行时立即执行?如果是后者,那么你可能需要将代码放在.ready()函数内部,它看起来像这样$(document).ready(function(){//code goes here}); - Alizoh
我正在使用 window.onload = initialize_function() 代码,这段代码应该放在哪里? - The Wanderer
尝试使用$(document).find('.tooltip').fadeOut(); - Alizoh
不起作用。我认为这是因为在文档中找不到“.tooltip”。只有在鼠标悬停后,“.tooltip”才会添加到文档中。 - The Wanderer
3个回答

3
参考Zoheiry的回答,这是我最终做的事情:
$('[data-sentence-tooltip="yes"]').on('mouseover', function(){
    setTimeout(function(){
    $('#enclosingParentDiv').find('.tooltip').fadeOut('fast');
  }, 1000);
}); 

需要注意的几点:

  1. 我对每个div应用了"mouseover",因为用户正在悬停在div中的内容上
  2. 我在父div中搜索.tooltip,因为tooltip被添加为同级元素。

2
添加以下类似的功能
$('[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);
});

这样做可以确保你的代码只会在你悬停在显示它的项目上后才寻找 .tooltip。

嗨,Zoheiry,感谢你的回答。我进一步修改了它以使其工作(请参见我的答案)。您能否编辑您的答案以反映这些更改,以便我可以接受您的答案。如果我把你的答案归功于自己,那就不公平了。 - The Wanderer

1
我通过在Chrome的检查元素下查看来弄清楚这个问题。不确定这是否完全可靠并且适用于其他浏览器。
$('input').on('mouseover', function() {
    if(!$(this).is(":focus"))
        $("#" + $(this).attr("aria-describedby")).delay(800).fadeOut(800);
});

如果从句是可选的,这使得代码只在焦点不在文本框上时有效。否则,工具提示将继续显示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接