引用事件侦听器中的工具提示,使其在悬停时保持打开状态



发现自己处于一个有点奇怪的位置,我必须在所有工具提示的实例化中引用工具提示。

$('body').tooltip({
    selector: '[data-toggle="tooltip"]',
    html: true,
    animation: false,
}).on("mouseenter", function (e) {
    e.stopPropagation();
    var _this = e.target;
    $(_this).tooltip("show");
    $(".tooltip").on("mouseleave", function () {
        $(_this).tooltip('hide');
    });
}).on("mouseleave", function (e) {
    e.stopPropagation();
    var _this = e.target;
    setTimeout(function () {
        if (!$(".tooltip:hover").length) {
            $(_this).tooltip("hide");
        }
    }, 300);
});

话虽如此,我怎么能:

  • 引用触发此jQuery调用的实际元素
  • 当实际工具提示或生成工具提示的元素悬停在其上时,是否保持工具提示打开

以下是指向JSFiddle原型的链接:https://jsfiddle.net/cwv57weu/8/

在'.on()'调用中,可以向匿名函数添加'event'参数。这将包含事件的所有数据,包括触发事件的元素(它将被引用为"target")。

}).on("mouseenter", function (event) {
    $(event.target).tooltip("show");
})

event参数包含大量数据,我会通过匿名函数中的console.log(event)来处理它,以了解哪些数据对您可用。

使用event.target

$('body').tooltip({
    selector: '[data-toggle="tooltip"]',
    html: true,
    animation: false,
}).on("mouseenter", function (e) {
    var _this = e.target;
    $(_this).tooltip("show");
    $(".tooltip").one("mouseleave", function () {
        $(_this).tooltip('hide');
    });
}).on("mouseleave", function (e) {
    var _this = e.target;
    setTimeout(function () {
        if (!$(".tooltip:hover").length) {
            $(_this).tooltip("hide");
        }
    }, 300);
});

e.target是事件发起的实际元素,而this是事件侦听器附加到的元素(相当于e.currentTarget)。

注意,由于事件冒泡,事件将在body之前的所有包含元素上激发。您可能希望使用e.stopPropagation()来防止冒泡,因此只处理最深的元素。

我还将.tooltip上的mouseleave处理程序更改为使用.one()。否则,每次输入内容时,都会在所有工具提示中添加另一个mouseleave处理程序,而不删除前一个,很快就会有数千个处理程序在运行(这就是为什么将事件处理程序绑定到其他事件处理程序中通常是错误的)。我真的不确定您是否需要mouseleave处理程序和您附加到body的处理程序。

最新更新