【问题标题】:Bug fix for a script that applies CSS to the title attribute将 CSS 应用于 title 属性的脚本的错误修复
【发布时间】:2014-11-02 17:53:56
【问题描述】:

下面的脚本将 CSS 类应用于 html 标题属性。出现脚本的原始页面在这里:How to change the style of Title attribute inside the anchor tag?

效果很好,但有一个小错误。如果 title 属性为空(<input type="text" title="">),它仍然会在屏幕上显示一个空的弹出框。

谁能帮忙解决这个问题?类似“如果标题属性没有值,则不应用 css,不显示弹出框。谢谢!

下面的脚本:

// Use a closure to keep vars out of global scope
(function () {
    var ID = "tooltip", CLS_ON = "tooltip_ON", FOLLOW = true,
    DATA = "_tooltip", OFFSET_X = 20, OFFSET_Y = 10,
    showAt = function (e) {
        var ntop = e.pageY + OFFSET_Y, nleft = e.pageX + OFFSET_X;
        $("#" + ID).html($(e.target).data(DATA)).css({
            position: "absolute", top: ntop, left: nleft
        }).show();
    };
    $(document).on("mouseenter", "*[title]", function (e) {
        $(this).data(DATA, $(this).attr("title"));
        $(this).removeAttr("title").addClass(CLS_ON);
        $("<div id='" + ID + "' />").appendTo("body");
        showAt(e);
    });
    $(document).on("mouseleave", "." + CLS_ON, function (e) {
        $(this).attr("title", $(this).data(DATA)).removeClass(CLS_ON);
        $("#" + ID).remove();
    });
    if (FOLLOW) { $(document).on("mousemove", "." + CLS_ON, showAt); }
}());

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    这边:

    $(document).on("mouseenter", "*[title]:not([title=''])" ...
    

    【讨论】:

      【解决方案2】:

      一种方法是在没有标题的情况下立即返回:

         $(document).on("mouseenter", "*[title]", function (e) {
              if (!$(this).attr('title')) return;
              // rest of code
          });
      

      @c-smile 的回答更简洁。

      【讨论】:

        猜你喜欢
        • 2017-04-12
        • 1970-01-01
        • 2017-08-05
        • 1970-01-01
        • 2023-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多