tooltip.js是一款HTML5 tooltips工具提示jQuery插件。tooltip.js可以通过js或html5 data属性来实例化一个tooltip。它的特点还有:

  • 可以自定义tooltip动画。
  • 内置暗色和亮色两种主题。
  • 可以自定义文字和阴影的颜色等属性。
  • 允许动态的改变tooltip的内容。
  • 允许在没有用户交互的情况下显示tooltip。

使用方法

在页面中引入jquery和tooltip.js文件,以及样式文件tooltip.css。

<script src='js/jquery.min.js'></script>
<script src='js/tooltip.js'></script>
<link rel="stylesheet" href="css/tooltip.css" type="text/css" />
                
通过js来初始化tooltip

第一种使用tooltip.js插件的方法是通过js来初始化tooltip。例如:

<span id="my-element">Hover Me</span>
                
$(document).ready(function(){
  $('#my-element').tooltip({
      // 配置参数
  });
});                  
                
通过data属性来初始化tooltip

第二种方法是通过HTML data属性和class来初始化tooltip。例如:

首先定义全局的tooltip属性:

$(document).ready(function(){
  ToolTip.init({
      delay: 400,
      fadeDuration: 250,
      fontSize: '1.0em',
      theme: 'light',                   
      textColor: '#757575',
      shadowColor: '#000',
      fontFamily: "'Roboto-Medium', 'Roboto-Regular', Arial"
  });
});                  
                

然后通过data-tip属性和tip-hotspotclass来定义一个tooltip。

<button class="tip-hotspot" data-tip="This is the tooltip text">Button text here</button>
                

配置参数

使用第一种通过js来初始化tooltip的方法时,可以使用下面的配置参数:

参数 是否必须 描述
text tooltip上显示的内容。
delay tooltip显示的延迟时间。默认为0。
fadeDuration 淡出的持续时间,单位毫秒,默认为250毫秒。
fontSize tooltip的字体大小,默认为1em。
theme tooltip的主题。可选有'dark'和'light'。
textColor 文字的颜色。
shadowColor 阴影的颜色。
fontFamily 字体族。默认为'Arial, Helvetica, sans-serif'。

示例:

$(document).ready(function(){
  $('#my-element').tooltip({text: '这是一个tooltip'});
});             
                

带参数的tooltip:

$(document).ready(function(){
  $('#my-element').tooltip({
    text: '这是一个tooltip',
    fontSize: '14px',
    theme: 'light',
    fontFamily: "'Roboto-Medium', 'Roboto-Regular', Arial",
    delay: 400
  });
});            
                

方法

使用第一种通过js来初始化tooltip的方法时,可以使用下面的方法:

setText:设置文字。

$('#my-element').tooltip('setText', 'This is the new tooltip text');                  
                

autoTip:自动显示tooltip。

$('#my-element').tooltip('autoTip', {MY OPTIONS});               
                

自动显示tooltip的可用配置参数有:

参数 是否必须 描述
displayDuration tooltip多久才被显示。默认为5000毫秒。
fadeOutDuration 淡出的持续时间,默认为1000毫秒。
onShowCallback tooltip出现时的回调函数。
onHideCallback tooltip隐藏时的回调函数。

示例:使用setText来设置文字,然后使用autoTip来自动显示tooltip。

$('#social-messages-button').tooltip('setText', 'You have 1 new message');
$('#social-messages-button').tooltip('autoTip', {
    displayTime: 4000,
    fadeOutDuration: 5000,
    onShowCallback: function(){
      // play notification sound
    }
});                  
                

tooltip.js插件的github地址为:https://github.com/ryanjairam/tooltip