当鼠标悬停在复选框的标签上时显示工具提示,当不悬停时隐藏。
HTML:<div style="margin: 2em 0 0 2em">
<label id="checkbox-label">
<input type="checkbox">Checkbox</label>
</div>
JS:
$('#checkbox-label').tooltip({
title: "This tooltip won't disappear when the checkbox is checked.",
placement: "right"
})
问题是当用户选中或取消选中复选框时,工具提示不会隐藏,直到用户单击屏幕上的其他位置。
当复选框被选中/未选中时,如何使此工具提示消失?
这里是一个JS提琴再现的问题:http://jsfiddle.net/eLax5hdq/5/
我刚刚遇到了同样的问题,但想到了一个不同的解决方案:
$('#checkbox-label').on('show.bs.tooltip change', function (e) {
$(this).blur();
});
仅供参考,尽管这个问题已经得到了回答。
为将来参考,当tooltip即将显示时,bootstrap将触发show.bs.tooltip事件。通过这种方式,您可以有条件地检查某些内容。如果你把事件传递给函数,如果条件不满足,你可以运行event. preventdefault()。
http://jsfiddle.net/SeanWessell/eLax5hdq/9/$('#checkbox-label').on('show.bs.tooltip change', function (e) {
$this = $(this);
if (e.type == 'show' && $this.find(":checkbox").is(":checked")) {
e.preventDefault();
} else if (e.type == 'change') {
$this.find(":checkbox").is(":checked") ? $this.tooltip('hide') : $this.tooltip('show');
}
});
使用$(this).tooltip("hide")
而不是$(this).tooltip("close")
,因为.tooltip()
不支持值为"close"
的参数
如Bootstrap文档中所述,tooltip
支持的方法是:.tooltip('hide')
, .tooltip('show')
, .tooltip('toggle')
和.tooltip('destroy')
。
用一个更简单的解决方案回答我自己的问题,但我将保留接受的答案。
默认情况下,Bootstrap在悬停和焦点上显示工具提示。单击复选框使元素保持焦点,这就是为什么工具提示在没有一些额外代码的情况下不会隐藏,如该问题的其他两个答案所示。
修复是指定我只希望工具提示悬停通过添加data-trigger="hover"
到<label>
元素。
总之,修改如下:
<div>
<label id="checkbox-label">
<input type="checkbox">Checkbox
</label>
</div>
:
<div>
<label id="checkbox-label" data-trigger="hover">
<input type="checkbox">Checkbox
</label>
</div>
触发器的默认值是'hover focus',因此工具提示在按钮被点击后保持可见,直到另一个按钮被点击,因为按钮是聚焦的。
$("[data-toggle ="tooltip").tooltip ({触发:"悬停"})