Tooltipster

Tooltipster是一个强大又灵活的jQuery插件,能够帮助您轻松创建带有CSS装饰的工具提示(Tooltip),让原本丑陋的工具提示变得时尚前卫、贴合情境。

示例

入门

1. 加载jQuery,并加入Tooltipster的插件文件

当你下载Tooltipster之后, 把tooltipster.css和 jquery.tooltipster.min.js移动到你根目录(项目目录)下的CSS目录和JavaScript的目录。接下来,加载jQuery并且包含Tooltipster的CSS和JavaScript文件在相应的标签里面:

<head>
...

    <link rel="stylesheet" type="text/css" href="css/tooltipster.css" />

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.0.min.js"></script>
    <script type="text/javascript" src="js/jquery.tooltipster.min.js"></script>

...
</head>

2. 编辑HTML元素的属性

为了让Tooltipster工作,我们首先为需要显示tooltip的标签添加.tooltip类(也可以是其他类名或者其他可以用来选择元素的方法)。接下来,我们通过(标签的)title属性来设置tooltip的内容。以下是一些例子:

为一张图片添加一个tooltip(气泡悬浮框):

<img src="my-image.png" class="tooltip" title="This is my image's tooltip message!" />

为已经有样式类的链接添加一个tooltip(气泡悬浮框):

<a href="http://calebjacob.com" class="ketchup tooltip" title="This is my link's tooltip message!">Link</a>

为一个div添加一个tooltip(气泡悬浮框):

<div class="tooltip" title="This is my div's tooltip message!">
    This div has a tooltip when you hover over it!
</div>

3. 激活Tooltipster

我们要做的最后一件事情是激活这个插件。为此,需将以下脚本添加到闭合标签</head>前(你可以使用任何你想要的选择器——在本例中,我们使用.tooltip类):

<head>

    ...

    <script>
        $(document).ready(function() {
            $('.tooltip').tooltipster();
        });
    </script>
</head>

4. 更进一步

目录


4.1 在Tooltip中嵌入HTML代码

Tooltipster允许你在tooltip(气泡悬浮框)中使用任何你能想到的HTML标记,这意味着说你可以插入图像和格式化文本标签。为了达到这个目的,推荐的方法(与上面的)有点不同:在脚本中通过jQuery对象来定义你的内容而不是(标签的)title属性:

<head>

    ...

    <script>
        $(document).ready(function() {
            $('#my-tooltip').tooltipster({
                content: $('<span><img src="my-image.png" /> <strong>This text is in bold case !</strong></span>')
            });
        });
    </script>
</head>
<body>

    <div id="my-tooltip">
        This div has a tooltip with HTML when you hover over it!
    </div>

</body>

另外一种(不太推荐)实现这个目的的方法是直接将编码好的HTML标记放到你的(标签的)title属性并将‘content As HTML’的选项设置为‘true’。在任何情况下,确保你对希望展示在tooltip(气泡悬浮框)上的内容有严格控制,比如不必要的<script>或者<iframe> 标记可能会给你的网站带来一个严重的安全问题。

<head>

    ...

    <script>
        $(document).ready(function() {
            $('.tooltip').tooltipster({
                contentAsHTML: true
            });
        });
    </script>
</head>
<body>

    <div class="tooltip" title="&lt;img src=&quot;my-image.png&quot; /&gt; &lt;strong&gt; This text is in bold case !&lt;/strong&gt;">
        This div has a tooltip with HTML when you hover over it!
    </div>

</body>

4.2 自定义Tooltipster的样式

通过编辑或是重写css/tooltipster.css文件,你可以轻松的改变Tooltipsters的样式。

Tooltipster有4个打包好的的主题可供选择。它们在本页的底部有演示。若要使用一个主题,只要在你的页面中引入对应的css文件(位于 css/themes文件夹)并在Tooltipster的设置中指定它的名字:

$('.tooltip').tooltipster({
    theme: 'tooltipster-noir'
});

当然,你也可以选择创建一个全新的主题来满足你的需求。为做到这一点,从下面的例子开始并且加入你的想法。当你完成之后,包含并指定你的主题就像使用Tooltipster现有的主题一样。

/* This is how you would create a theme called "my-custom-theme": */

.my-custom-theme {
	border-radius: 5px;
	border: 2px solid #000;
	background: #4c4c4c;
	color: #fff;
}
/* Use this next selector to style things like font-size and line-height: */
.my-custom-theme .tooltipster-content {
	font-family: Arial, sans-serif;
	font-size: 14px;
	line-height: 16px;
	padding: 8px 10px;
}

4.3 自定义Tooltipster的功能

Tooltipster的选项为你提供了广泛的变量值,使你的tooltip(气泡悬浮框)达到你心仪的效果。想要了解更多的选项,请阅读选项部分。这边只是一点东西仅供参考:

$('.tooltip').tooltipster({
   animation: 'fade',
   delay: 200,
   theme: 'tooltipster-default',
   touchDevices: false,
   trigger: 'hover'
});

选项

animation

fade, grow, swing, slide, fall 决定tooltip将如何动态地显示和隐藏。你可以随意地在tooltipster.css文件上修改或创建自定义转换效果。在IE9和IE8中,所有的动画效果(animation)将(退化)默认为由使用Javascript实现的渐隐(fade)效果Default: 'fade'

arrow

boolean 为tooltip增加了“聊天气泡箭头”。Default: true

arrowColor

hex code / rgb 为“聊天气泡箭头”选择一个特定的颜色。Default: 将继承tooltip的背景颜色。

autoClose

boolean 当autoClose值为false时,tooltip将永远不会关闭,除非你自己调用hide方法。 Default: true

content

string, jQuery object 一旦设置,这将覆盖tooltip的内容。Default: null

contentAsHTML

boolean 如果tooltip的内容(content)是以字符串形式提供的,它会默认显示为纯文本。当这个内容(content)需要作为HTML解析时,设置这个选项为true。Default: false

contentCloning

boolean 如果你为内容(content)选项提供一个jQuery对象,contentCloning选项决定了tooltip具体使用该对象的拷贝还是对象本身,来作为content的值。Default: true

debug

boolean 当你犯了某些错误时,Tooltipster日志将会通知控制台。设置为false以禁用日志记录。 Default: true

delay

integer tooltip启动动画所延迟的时间值(毫秒)。Default: 200

minWidth

integer 为tooltip设置一个最小宽度值。Default: 0 (auto width)

maxWidth

integer 为tooltip设置一个最大宽度值。Default: null (no max width)

functionInit

function 创建一个仅在实例化时被调用的自定义函数。如果这个函数返回一个值,这个值将成为tooltip的content选项的值。查看高级用法 以了解更多。 Default: function(origin, content) {}

functionBefore

function 创建一个在tooltip打开之前被调用的自定义函数。这个函数可能阻止或延迟tooltip的打开。查看 高级用法 to 以了解更多。 Default: function(origin, continueTooltip) { continueTooltip(); }

functionReady

function 创建一个当tooltip 和它的内容添加到DOM后被调用的自定义函数。 Default: function(origin, tooltip) {}

functionAfter

function 创建一个仅当tooltip已经被关闭且从DOM中删除后被调用的自定义函数。 Default: function(origin) {}

hideOnClick

boolean 当值为true时,如果单击初始对象(origin),tooltip将关闭。此选项仅适用于“触发条件(trigger)”为“悬停(hover)”而且“自动关闭(autoClose)”值为false时。Default: false

icon

string, jQuery object 当使用iconDesktop或iconTouch选项时,这个选项将为你设置icon的内容(content)。 Default: '(?)'

iconCloning

boolean 如果你为“icon”选项提供一个jQuery对象,而iconCloning选项设置为该对象的一个克隆者,则该对象实际上应该被使用。 Default: true

iconDesktop

boolean 在非触摸设备上,在内容旁边生成一个用以激活tooltip的iconDefault: false

iconTheme

CSS class 当使用iconDesktop或iconTouch选项时,用来设置icon类(用于定制icon样式)。 Default: 'tooltipster-icon'

iconTouch

boolean 在触摸设备(比如平板电脑、手机等)上,在内容旁边生成一个用以激活tooltip的iconDefault: false

interactive

boolean 使得用户与tooltip之间可以进行交互。除非将自动关闭设置成false,否则当用户移开或点击tooltip外的区域时,tooltip依然会关闭。Default: false

interactiveTolerance

integer 如果tooltip是交互式的并且被一个悬停事件激活,设置tooltip的悬停激活时间(ms)。Default: 350

multiple

boolean 允许你将多个tooltip放在当个元素上。进一步说明请查看下文。Default: false

offsetX

integer tooltip从原始位置向左或向右偏移(以像素为单位)。Default: 0

offsetY

integer tooltip从原始位置向上或向下偏移(以像素为单位)。Default: 0

onlyOne

boolean 如果为真,一次只能有一个tooltip被激活。然而非自动关闭的tooltip将不会被关闭。Default: false

position

right, left, top, top-right, top-left, bottom, bottom-right, bottom-left 设置tooltip的位置。Default: 'top'

positionTracker

boolean 当原始对象移动时重新调整tooltip的位置(tooltip打开的状态下)。这个选项会影响到性能表现,我们建议你仅在需要的时候开启。 Default: false

positionTrackerCallback

function 在定位跟踪重新将tooltip重定位后调用。默认:tooltip的激活方式为悬停(hover)和自动关闭(autoClose)为false时默认为关闭tooltip

restoration

'none', 'previous' or 'current' 在HTML元素中的一个TITLE属性被destroy方法调用销毁后,要恢复该属性时使用。这个属性可省略,可恢复Tooltipster初始化前存在的值,也可恢复当前内容的字符串字段值。注意:若某一元素有多个悬浮窗,只有 最后被销毁的那个才可以恢复。Default: 'current'

speed

integer 设置animation动画属性的速度。 Default: 350

timer

integer 关闭前悬浮窗可存在的时间。(tooltip自动关闭的时间)Default: 0 (disabled)

theme

CSS class 设置你的悬浮窗口的主题。 Default: 'tooltipster-default'

touchDevices

boolean 如果设为false,悬浮窗不会在触屏设备上显示,除非你自己利用“show”方法打开。设备上带有鼠标指针的触摸手势仍可打开悬浮窗。Default: true

trigger

hover, click, custom 设置悬浮窗如何触发或关闭。详见“高级应用”部分以便学习如何自定义触发器。Default: 'hover'

updateAnimation

boolean 假如悬浮窗处于开启状态中,而此时其内容恰好更新,那么在更新时播放一段细致的更新动画。 Default: true

高级用法

强大的Tooltipster API

Tooltipster API的设计理念是:尽可能灵活、易于使用(感谢 glebtv 的启发)。借助API,你可以创建自定义触发器(trigger),动态更改工具提示的内容(无论该工具提示当前是否已开启),撤销Tooltipster增强效果(即:恢复为原生态的工具提示),以及更改工具提示的位置。

让我们来大致看一下所有API方法:

// 为之后创建的所有工具提示设定默认配置
$.fn.tooltipster('setDefaults', {
  position: 'bottom'
});

// 显示某个工具提示('callback'参数是可选的)
$(...).tooltipster('show', callback);

// 隐藏某个工具提示('callback'参数是可选的)
$(...).tooltipster('hide', callback);

// 临时禁用一个工具提示,使其无法被开启
$(...).tooltipster('disable');

// 如果一个工具提示被设为禁止开启,调用本方法能解除禁用
$(...).tooltipster('enable');

// 关闭工具提示,并撤销Tooltipster增强效果(即:恢复为原生态的工具提示)
$(...).tooltipster('destroy');

// 获取某个工具提示的当前内容(如果jQuery选择器返回多个元素的话,本方法只返回第一个元素的内容)
$(...).tooltipster('content');

// 更改工具提示的内容
$(...).tooltipster('content', myNewContent);

// 读取某个选项的值
$(...).tooltipster('option', optionName);

// 设置某个选项的值(该方法存在风险。对于因调用该方法而引发的问题,我们不提供支持。)
$(...).tooltipster('option', optionName, optionValue);

// 调整工具提示的位置和大小
$(...).tooltipster('reposition');

// 获取某个工具提示的HTML根元素
$(...).tooltipster('elementTooltip');

// 获取某个工具提示图标的HTML根元素。如果不存在图标的话,返回'undefined'
$(...).tooltipster('elementIcon');

使用案例

1.配合AJAX,动态加载和更新Tooltip的内容

Tooltipster能在工具提示每次打开前 (functionBefore) 或实例化 (functionInit)时,自动调用一个同步或异步的函数。该特性有一个相当实用之处:用于配合AJAX来动态加载和更新工具提示的内容。

functionBefore示例:
以下是一个在functionBefore()中异步调用AJAX的例子。在本例中,用从AJAX获取的内容来替换初始的提示文字“正在加载中”。当AJAX成功获取到内容后,使用jQuery的$.data()方法,将状态属性’ajax’标记为“cached(已缓存)”。这样,在下次打开工具提示时,就可以直接显示上次缓存的内容,而不必再次调用AJAX来获取内容。

$('.tooltip').tooltipster({
    content: '正在加载中...',
    functionBefore: function(origin, continueTooltip) {
        //本匿名函数是异步的,使得AJAX正在获取数据的同时,工具提示能弹出来并显示“正在加载中…”(注:根据文档,functionBefore函数返回后,工具提示才能弹出)

        continueTooltip();

        //检测内容是否已缓存(若已经缓存,则无需重新获取)
        if (origin.data('ajax') !== 'cached') {
            $.ajax({
                type: 'POST',
                url: 'example.php',
                success: function(data) {
                    //用通过AJAX获得的内容来替换原有内容,并把状态标记为“cached(已缓存)”
                    origin.tooltipster('content', data).data('ajax', 'cached');
                }
            });
        }
    }
});

functionInit示例:
然而,或许你只需要调用一次自定义函数。此时应使用functionInit()。该函数只在开始实例化时被调用一次。在下面的例子中,该函数用于检查工具提示的当前内容并更新内容。由于此时读取和设置值的API还未初始化,本例中的处理方法与functionBefore()的例子略有不同。

$('.tooltip').tooltipster({
    functionInit: function(origin, content) {

        if (content === 'This is bad content') {

            // 当AJAX请求加载完成时,更改工具提示的内容
            $.ajax({
                type: 'POST',
                url: 'example.php',
                success: function(data) {
                    origin.tooltipster('content', '已成功加载新内容 : ' + data);
                }
            });

            // 函数返回值将覆盖工具提示的原有内容
            return '正在加载新内容,请稍候...';
        }
        else {
            // 函数不返回任何内容。因此,工具提示的内容不会改变,初始化过程正常继续执行。
        }
    }
});

2.手动显示、隐藏Tooltip

By default and according to the 'trigger' option, Tooltipster automatically shows tooltips upon users' mouse clicks or mouse hovering (or their touch-gesture equivalents). In addition to this, you may also manually open or close a tooltip at anytime with a simple javascript command.

To achieve this, Tooltipster has the 'show' and 'hide' methods. Both of them may receive an optional 'callback' parameter, which represents a function you'd like to call when the tooltip is done animating.

Here's an example of how you could launch a specific tooltip on page load and close it when any key on your keyboard is pressed. This will still preserve the default hover trigger.

<span class="tooltip" id="example" title="My tooltip content">Example</span>
$(document).ready(function() {

   // first on page load, initiate the Tooltipster plugin
   $('.tooltip').tooltipster();

   // then immediately show the tooltip
   $('#example').tooltipster('show');

   // as soon as a key is pressed on the keyboard, hide the tooltip.
   $(window).keypress(function() {
      $('#example').tooltipster('hide');
   });
});

You may also provide a function as the callback parameter of the show/hide methods. The callback functions are called in the context of the tooltipstered element. If the tooltip is already in the state you are asking for (open/closed), the callback is executed immediately. Please note that if the show/hide action is somehow cancelled before it has completed its animation, the callback function will never be called.

$(document).ready(function() {

   $('.tooltip').tooltipster();

   $('#example').tooltipster('show', function() {
       alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content'));
   });

   $(window).keypress(function() {
      $('#example').tooltipster('hide', function() {
         alert('The tooltip is now fully closed');
      });
   });
});

3.更改Tooltip的内容

It's easy as pie to update a tooltip's content - whether it's open or closed. Depending on your selector, you can update multiple tooltips at once or just one:

$('#my-special-element').tooltipster('content', 'My new content');

By default, Tooltipster will play a subtle animation when the content changes. To tweak the animation, check out the '.tooltipster-content-changing' class in your tooltipster.css file. It's important to note that only CSS transforms will be animated. To disable this animation, set updateAnimation to false.

4.在单个元素上添加多个Tooltip

单个HTML元素上可以添加多个工具提示。它们拥有各自的触发器(trigger)和属性,互不影响。要实现这个效果,只需在初始化工具提示时,把'multiple'选项设为true即可。该属性设为true,将带来2个变化:

第一,实例化方法的返回类型由“Tooltipster对象”变为“Tooltipster对象数组”。

第二,所有API仍然可用,但调用API的方法改变了。现在,必须通过Tooltipster对象(而不是jQuery选择器$(...))来调用Tooltip的各个API方法。

// 首先,与创建单个Tooltip的方法相同,在my-element元素上添加第一个Tooltip。第一个Tooltip可以不指定'multiple'选项。
$('#my-element').tooltipster({
	content: '第一个工具提示',
	position: 'top'
});

// 然后,在my-element元素上创建第二个Tooltip,把返回的Tooltipster对象数组保存到变量中,以备后续使用。
var tooltipsterObjects = $('#my-element').tooltipster({
	// 注意区别:对于同一元素上创建的第二个工具提示,必须注明Tooltip的内容(content)。因为创建首个Tooltip时,已经自动移除了HTML元素的title属性,所以无法从title属性读取content。
	content: '第二个工具提示',
	multiple: true,
	position: 'bottom'
});

// 由于本例中jQuery选择器只返回一个HTML元素,所以数组中只包含一个Tooltipster对象。
// (如果jQuery选择器返回了多个HTML元素,数组将包含多个与之对应的Tooltipster对象。数组中对象的顺序与HTML元素的顺序一致。)
var tooltip2 = tooltipsterObjects[0];

// 用这个Tooltipster对象来调用各个API方法
tooltip2.content('New content for my second tooltip').show();
// 通过这种方式,可以调用本文档中的所有API
var element = tooltip2.elementTooltip();

// -----------------------------------------------------------
// 如果以普通的方式调用API,API只会作用于该元素的第一个Tooltip,其余的Tooltip不受影响。
$('#my-element').tooltipster('content', 'New content for my first tooltip')
// 在创建首个Tooltip时,也可以加上multiple:true。加上该属性后,方法会返回一个对象数组。
var tooltipsterObjects = $('#my-element').tooltipster({
	content: '第一个工具提示',
	multiple: true
});

// 也可以用这种方法来在首个Tooltip上调用API:
var tooltip1 = tooltipsterObjects[0];
tooltip1.content('New content for my first tooltip').show();

注意:使用.tooltipster('destroy')方法销毁同一元素上的多个Tooltip时,只有最后一个被销毁的Tooltip的content(内容)会被回填到元素的title属性中。(把内容回填到元素的title属性中,是为了还原为“原生态的工具提示”)

5.为残障人士阅读Tooltip的内容提供便利

The W3C issued a recommendation to make websites more accessible to persons with disabilities. This recommendation is known as WAI-ARIA (or simply ARIA), which stands for Web Accessibility Initiative - Accessible Rich Internet Applications.

Accessible tooltips can be powered by Tooltipster. To do this, one solution is to actually manipulate in parallel two tooltips which will share the same content :
- the ARIA tooltip, which is invisible on the screen but readable by ARIA-compatible software
- the Tooltipster tooltip, which is visible on the screen but does not appear as an ARIA-compatible element

A basic example : imagine that we want to put a tooltip on a text input field. As for the HTML part, you would write :

<input id="myfield" type="text" aria-describedby="myfield_description" />
<span id="myfield_description" role="tooltip">Please insert your name here</span>

As for the CSS part, write this :

#myfield_description {
	display: none;
}

And finally, you could initiate Tooltipster like this :

$('#myfield').tooltipster({
    functionInit: function(){
        return $('#myfield_description').html();
    },
    functionReady: function(){
        $('#myfield_description').attr('aria-hidden', false);
    },
    functionAfter: function(){
        $('#myfield_description').attr('aria-hidden', true);
    }
});

// if in addition you want the tooltip to be displayed when the field gets focus, add these custom triggers :
$('#myfield')
    .focus(function(){
        $(this).tooltipster('show');
    })
    .blur(function(){
        $(this).tooltipster('hide');
    });

6.来自社区的使用案例

Using Tooltipster alongside jQuery Validate
(如何使用 Tooltipster来显示jQuery Validate的错误信息?)
by sparky672

Did you do something awesome with Tooltipster? Tell me and I'll post it up here!

主题

Tired of the same old? Four other rocking themes are available for your tooltips, and you can always create yours ! Share them with us on GitHub !

Default Light Punk Noir Shadow

讨论交流

Share thoughts, questions, & bugs!

Head on over to Tooltipster's issue tracker on GitHub: https://github.com/iamceege/tooltipster/issues

Before opening a new issue, please be sure to search through the backlog to see if your question or bug has been / is being resolved. Thank you! :)