jQuery 试图将工具提示放在悬停的元素上

Rya*_*P13 2 jquery jquery-plugins

我正在编写自己的工具提示功能,如下所示:

$(".tip_holder").hover(
  function() {

      var $containerWidth = $(this).width();

      var $containerHeight = $(this).height();

      var $tipTxt = $(this).text();

      var $tipTitle = $(this).attr('title');

      var $offset = $(this).offset();

      $('#icis_dashboard').prepend('<div id="tooltip">' + $tipTxt + '</div>');

      $('#tooltip').css({
          'position': 'absolute'
      });

      var $tipWidth = $('#tooltip').width();

      var $tipHeight = $('#tooltip').height();

      $('#tooltip').css({
          'top': $offset.top - ($tipHeight + 5),
          'left': $offset.left,
          'padding': '0 5px 5px'              
      });

  },
  function() {
      $('#tooltip').remove();
  }
);
Run Code Online (Sandbox Code Playgroud)

但是,我无法将工具提示居中放置在我悬停的元素上。我需要将其缩放到悬停的任何大小元素。

我很欣赏有许多插件可以实现此功能,但我想编写自己的插件,以便工具提示 div 只会出现在代码中的同一位置,以便我的测试人员可以对其进行测试。这是他的要求,让他的生活更轻松:(

Nal*_*lum 5

如果您使用的是最新版本的 jQuery 和 jQuery-ui,那么您可以使用位置工具将工具提示居中放置在元素上方。

http://jqueryui.com/demos/position/

编辑以回应作者的回答。

$(".tip_holder").hover(function(){
    var currentTipHolder = $(this);
    var $tipTxt = $(this).text();
    var $tipTitle = $(this).attr('title');

    $('#icis_dashboard').prepend('<div id="tooltip">' + $tipTxt + '</div>');

    // jQueryUI position
    $('#tooltip').position({
        of: currentTipHolder,
        at: 'center top',
        my: 'center bottom'
    });
},function() {
    $('#tooltip').remove();
});
Run Code Online (Sandbox Code Playgroud)

  • @android.nick -- 如果您从 Google CDN 调用 jqueryui,不仅会并行发出 HTTP 请求,而且您的访问者很可能已经在缓存中拥有它,因此您的页面权重成本实际上是0——当然比编写自己的实现便宜。 (2认同)