twitter-bootstrap 使用 javascript 显示和隐藏引导工具提示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37938425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show and hide bootstrap tooltip using javascript
提问by Alexander Seredenko
I need to show bootstrap tooltip when user click on element and condition is false. I've written code for this:
当用户单击元素并且条件为假时,我需要显示引导工具提示。我为此编写了代码:
<div data-toggle="tooltip" title="You must to log in!" class="stars">425</div>
and Javascript:
和 Javascript:
$(".statistics .stars").click( function(){
if (! user.isLogin){
$(this).tooltip("show");
setTimeout(function(){
$(this).tooltip( 'hide' );
}, 2000);
}
});
When I don't click I can see default tooltip on hover (I don't need it) and when I click, tooltip don't hide after 2 seconds. How to solve this problems?
当我不点击时,我可以看到悬停时的默认工具提示(我不需要它),当我点击时,工具提示不会在 2 秒后隐藏。如何解决这些问题?
回答by Almis
First you need to set tooltip to be manual, now it will not popup on hover
首先你需要将工具提示设置为手动,现在它不会在悬停时弹出
$('div').tooltip({trigger: 'manual'});
After that you need to save div element before using it inside setTimeout because thisoutside of setTimeout and thisinside of setTimeout is different.
之后你需要在 setTimeout 内部使用它之前保存 div 元素,因为 setTimeoutthis外部和 setTimeoutthis内部是不同的。
$('div').click(function(){
var tt = $(this);
if (! user.isLogin){
tt.tooltip("show");
setTimeout(function(){
tt.tooltip( 'hide' );
}, 2000);
}
});
Here is the updated jsfiddle
这是更新的jsfiddle
回答by timhysniu
This should solve your problem:
这应该可以解决您的问题:
$(".statistics .stars").click( function(){
if (! user.isLogin){
var $el = $(this);
$el.tooltip("show");
setTimeout(function(){
$el.tooltip( 'hide' );
}, 2000);
}
});

