Clear title property while JQuery tooltip shows

I am using some very simple JQuery to create a hovering tool tip using text stored in elements' title attribute. It's working okay, but I need to stop the browser's default title behaviour occurring at the same time (or after the slight delay on hover).

I think JQuery's .on() functionality may not be the best way, although I am trying to use the latest functionality (that I am aware of!).

Currently if I clear the existing title value, the actual tooltip appears but is empty. I think that is because the code runs continuously while the mouse is over the element.

Can anyone offer a way to stop the browser's title text appearing, but restore the original value of title onmouseout? I need the code to work with JQuery 1.10.1+ with XHTML1.1 compatibility.

Thanks.

    $(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(/(rn|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
            }
        });
    }

Try making these lines:

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

do this instead:

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

What the code above does is that if the title attribute is empty, the or ( || ) operator will then look for the title within the data.


Use $(selector).removeAttr('title'); to achieve your desired results.

链接地址: http://www.djcxy.com/p/14210.html

上一篇: jQuery.extend()深入克隆嵌套对象

下一篇: 在JQuery工具提示显示时清除标题属性