伪禁用元素上的 jQuery UI 工具提示

问题描述

我想在具有 ui-state-disabled 类的文本输入上显示 tooltip

我查看了 tooltip source code 并找不到可以检查该特定类的内容。所以我不知道为什么它不会显示

据我所知,元素本身没有被禁用,它们只是应用了一个类。

那么,如何在具有该类的元素上显示工具提示?我不想使用包装器或类似的东西。也许通过小部件工厂扩展...

这是一个示例代码

HTML

<input name="#1" class="text" data-tooltip="message A">
<input name="#2" class="text" data-tooltip="message B">
<br>
<button id="disable">disable input #2</button>
<button id="enable">enable input #2</button>

JS

$(".text").each(function()
{
    $(this).tooltip({
        content: $(this).data("tooltip"),items: ".text"      
    });
});

$("#disable").click(function()
{
    $("input[name='#2']").addClass("ui-state-disabled");
});

$("#enable").click(function()
{
    $("input[name='#2']").removeClass("ui-state-disabled");
});    

小提琴https://jsfiddle.net/hn1o4qs2/

解决方法

查看文档 (http://api.jqueryui.com/tooltip/):

一般来说,被禁用的元素不会触发任何 DOM 事件。 因此,无法正确控制工具提示 禁用元素,因为我们需要监听事件来确定何时 显示和隐藏工具提示。因此,jQuery UI 不会 保证对附加到禁用的工具提示的任何级别的支持 元素。不幸的是,这意味着如果您需要工具提示 禁用元素,您可能最终会得到混合的本机工具提示 和 jQuery UI 工具提示。

使用包装器的解决方案

您的 HTML:

<span class="input-container" data-tooltip="message A">
  <input name="#1" class="text">
</span>
<span class="input-container" data-tooltip="message B">
  <input name="#2" class="text">
</span>
<br>
<button id="disable">
disable input #2
</button>
<button id="enable">
enable input #2
</button>

您的 JavaScript

$(".input-container").each(function()
{
    $(this).tooltip({
        content: $(this).data("tooltip"),items: ".input-container"      
    });
});
// ... The rest is the same

带有假禁用属性的解决方案

在这里,您可以使用 readonly 属性和自定义类来禁用输入。

游乐场https://jsfiddle.net/5gkx8qec/

,

正如我在我的问题中所述,我需要在不添加容器或类似内容的情况下使其正常工作。而且我愿意以某种方式扩展小部件...

所以我更仔细地阅读了源代码,并在整个存储库中搜索了 ui-state-disabled,发现在 widget.js 中有一个 _on() 方法,该方法在某些时候对该类执行检查和一个名为 suppressDisabledCheck

的标志

代码中的注释说

// Allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts

这非常重要,它给了我这个检查可以被覆盖的线索。所以在谷歌和the widget factory had the answer中快速搜索:

自动处理禁用的小部件:如果小部件被禁用或 该事件发生在具有 ui-state-disabled 类的元素上, 不调用事件处理程序。可以用 抑制DisabledCheck参数。

所以基本上我是这样做的:

$.widget("ui.tooltip",$.ui.tooltip,{
    options: {
        allowOnDisabled: false
    },_on: function()
    {
        var instance = this;

        this._super(instance.options.allowOnDisabled,{
            mouseover: "open",focusin: "open",mouseleave: "close",focusout: "close"
        });
    }
});

然后像这样使用它:

$(".text").each(function()
{
    $(this).tooltip({
        allowOnDisabled: true,content: $(this).data("tooltip"),items: ".text"      
    });
});