1

我正在使用一些非常简单的 JQuery 来使用存储在元素title属性中的文本创建悬停工具提示。它工作正常,但我需要停止浏览器的默认title行为同时发生(或在悬停时稍有延迟)。

在此处输入图像描述

我认为 JQuery 的.on()功能可能不是最好的方法,尽管我正在尝试使用最新的功能(我知道!)。

目前,如果我清除现有title值,则会出现实际的工具提示但为空。我认为这是因为当鼠标悬停在元素上时代码会连续运行。

在此处输入图像描述

谁能提供一种方法来阻止浏览器的文本出现,但恢复onmouseouttitle的原始值?title我需要代码与具有 XHTML1.1 兼容性的 JQuery 1.10.1+ 一起使用。

谢谢。

    $(document).ready(function () {
        $('<div/>', { id: 'ttfloat', 'class': 'tooltip' }).appendTo('body');
        BuildTipsV3();
    });

    function pageLoad() { // fired by ASP.NET after partial postback
        BuildTipsV3();
    }

    //var temptt;

    function BuildTipsV3() {
        $("[title]").on({
            mouseenter: function () {
                var o = $(this).offset();
                var y = o.top + 18;
                var x = o.left;
                temptt = $(this).attr("title"); // temp storage
                $(this).data('title', temptt);
                //$(this).attr('title', '');
                var tooltip = temptt;
                tooltip = tooltip.replace(/(\r\n|\n|\r)/gm, "<br/>");
                $("#ttfloat").css({top:y, left:x})
                             .html(tooltip)
                             .show();
            },
            mouseleave: function () {
                $("#ttfloat").hide();
                $(this).attr('title', $(this).data('title')); // reset for accessibility
            }
        });
    }
4

2 回答 2

2

尝试制作这些行:

temptt = $(this).attr("title"); // temp storage
$(this).data('title', temptt);
//$(this).attr('title', '');
var tooltip = temptt;

改为这样做:

var $this = $(this),
    tooltip = $this.attr('title') || $this.data('title');
$this
    .attr('title', '')
    .data('title', tooltip);

上面的代码所做的是,如果 title 属性为空,则 or ( ||) 运算符将在数据中查找标题。

于 2013-07-15T16:56:59.820 回答
1

用于$(selector).removeAttr('title');达到您想要的结果。

于 2013-07-16T14:29:38.963 回答