在下面,我将在单击按钮后打开 p
元素的工具提示,并在再次单击按钮时关闭工具提示。
$(document).ready(function() {
var obj = null;
$('input').click(function() {
if (obj == null) {
obj = $('p');
obj.tooltip({
items: 'p',
content: 'Some help'
});
obj.tooltip("open");
} else {
obj.tooltip('disable');
obj = null;
}
});
$('.help').mouseenter(function(e) {
e.stopImmediatePropagation();
});
$('.help').mouseleave(function(e) {
e.stopImmediatePropagation();
});
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<input type='button' value='Click me' />
<p class='help'>
Some text
</p>
我现在尝试做的事情是相同的,只是当单击按钮时我将类“help”动态添加到 p
元素中。工具提示不再保持打开状态,而是在鼠标悬停时消失。我观察到 mouseenter()/mouseleave()
处理程序没有触发,因此我用 on()
替换了它们。事件现在触发,但工具提示仍然关闭。
$(document).ready(function() {
var obj = null;
$('input').click(function() {
if (obj == null) {
obj = $('p');
obj.tooltip({
items: 'p',
content: 'Some help'
});
obj.tooltip("open");
obj.addClass('help'); // Added statically in DOM in above snippet
} else {
obj.tooltip('disable');
obj = null;
}
});
$(document.body).on('mouseenter', '.help', function(e) {
//console.log('on mouseenter');
e.stopImmediatePropagation();
});
$(document.body).on('mouseleave', '.help', function(e) {
//console.log('on mouseleave');
e.stopImmediatePropagation();
});
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<input type = 'button' value = 'Click me' />
<p>
Some text
</p>
最佳答案
一旦离开Some text
后触发mouseleave
事件,工具提示似乎就会被隐藏。除非您需要 mouseleave 函数用于其他用途,否则您可以从工具提示中完全禁用此事件以达到您想要的结果。
obj.tooltip("open");
obj.toggleClass("help"); // Toggle help class
obj.off("mouseleave"); // Remove the event from the tooltip
jsFiddle:https://jsfiddle.net/c1f0ft8j/
关于javascript - 防止动态添加类的 jQuery 工具提示在 mouseleave 上关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38252956/