【问题标题】:jQuery UI Tooltip: Close on click on tooltip itselfjQuery UI 工具提示:单击工具提示本身时关闭
【发布时间】:2019-11-16 22:06:42
【问题描述】:
我有一个带有 jQuery UI 工具提示的页面,该页面最初打开并在 mouseout 事件时关闭它被禁用。
现在,我希望工具提示在用户单击它本身后关闭,而不是在显示工具提示的元素上(与此处的许多其他答案一样)。
作为一种可能的解决方案,我认为我可以将click 处理程序添加到工具提示的 div 并从那里关闭它。但我找不到使用 Tooltip 小部件 API 获取工具提示 div 或以其他方式附加处理程序的标准方法。
我在上述方法的正确轨道上吗?或者如何以不同的方式实现我所追求的目标?
JSFiddle 说明我目前拥有的东西。
【问题讨论】:
标签:
javascript
jquery
html
jquery-ui
jquery-ui-tooltip
【解决方案1】:
我找到了一个相对简单的解决方案,无需通过在工具提示的 open 事件中附加 click 处理程序并在此处关闭工具提示来破解工具提示 API:
$('.first')
.tooltip({
content: 'Click to close',
position: { my: 'left center', at: 'right center' },
items: '*'
open: function (event, ui) {
var $element = $(event.target);
ui.tooltip.click(function () {
$element.tooltip('close');
});
},
})
.tooltip('open')
.on('mouseout focusout', function(event) {
event.stopImmediatePropagation();
});
JSFiddle
【解决方案2】:
试试这个:
$(document).ready(function(){
$('.first')
.tooltip({ content: 'Click to close', position: { my: 'left center', at: 'right center' }, items: '*' })
.tooltip('open')
.on('mouseout focusout', function(event) {
event.stopImmediatePropagation();
})
// when the tooltip opens (you could also use 'tooltipcreate'), grab some properties and bind a 'click' event handler
.on('tooltipopen', function(e) {
var self = this, // this refers to the element that the tooltip is attached to
$tooltip = $('#' + this.getAttribute('aria-describedby')); // we can get a reference to the tooltip via the `aria-describedby` attribute
// bind a click handler to close the tooltip
$tooltip.on('click', function() {
$(self).tooltip('close');
});
});
});
【讨论】:
-
您的解决方案有效!但是,您对this one 怎么看?如果不通过节点属性获取工具提示,它看起来更简单。
【解决方案3】:
试试这个:
$(document).ready(function(){
$('.first').on('mouseout focusout', function(event) {
event.stopImmediatePropagation()
})
.tooltip({ content: 'Click to close', position: { my: 'left center', at: 'right center' }, items: '*' }).tooltip('open');
$( "body" ).delegate( ".ui-tooltip", "click", function() {
$('.first').tooltip('close');
});
});
见小提琴here
【讨论】:
-
谢谢!然而,这段代码在工具提示第一次关闭之前只能工作一次 (JSFiddle),因为我们需要在每次工具提示出现时重新绑定 click 处理程序。
-
【解决方案4】:
如果您只想在点击“X”时关闭,则基于 Alexes 的回答:
$(".t1").tooltip({
content: "<div><div class='tit'>Some super titlet</div> <div class='x'>x</div><div class='con'>Some content super super long</div></h1>",
disabled: true,
width:550,
tooltipClass: "myClass",
open: function (event, ui) {
var $element = $(event.target);
ui.tooltip.each(function () {
$("div.x",this).click(function () {
$element.tooltip('close');
});
});
},
}).on('mouseout focusout', function(event) {
event.stopImmediatePropagation();
});
$(".tooltip").click(function() {
$(this)
.tooltip("open")
});
在这里查看:http://jsfiddle.net/analienx/h639vzaw/73/