JQuery按位置显示元素 - 如果父屏幕在屏幕外,工具提示应该改变位置

时间:2014-06-03 09:20:41

标签: javascript jquery tooltip mouseover offset

我的工具提示显示正确,但如果我向下滚动工具提示偏移刹车。

如果这是在屏幕外,我如何计算父母的偏移位置?

工具提示应在屏幕上正确显示! DEMO

Jquery的:

$.fn.tooltip = function () {
     var $el = $(this);
     var $w = $(window);
     var timer;
     var delay = 500;

     $el.mouseenter(function (e) {
         timer = setTimeout(function () {
             var $c = $(e.currentTarget);
             var $tt = $('<div class="tooltip fade right"><div class="arrow"></div><h3 class="popover-title" style="display: none;"></h3><div class="popover-content"><article class="default"><h1>Anchorman 2: The Legend Continues</h1><ul><button>£10.99 Buy</button><button>£3.49 Rent</button><p>Hilarious comedy sequel starring Will Ferrell and Steve Carell.</p></article></div></div>').appendTo($(e.currentTarget).closest('.item')).fadeIn(300);

             $tt.toggleClass('horiz-offscreen', $w.width() < $tt.outerWidth() + $tt.offset().left);
             if ($w.height() < $tt.outerHeight() + $tt.offset().top) {
                 $tt.css('top', $w.scrollTop() + $w.height() - $c.position().top - $tt.outerHeight());
             }
         }, delay);
     });

     $el.mouseleave(function (e) {
         $('.tooltip', e.currentTarget).fadeOut(500, function () {
             $(this).remove();
         });
         clearTimeout(timer);
     });

 };

 $('.item').tooltip();

1 个答案:

答案 0 :(得分:0)

试试这个!你需要用css膨胀一下。 http://fiddle.jshell.net/j7MWE/3/

function isScrolledIntoView(elem) {
          var docViewTop = $(window).scrollTop(),
              docViewBottom = docViewTop + $(window).height(),

              elemTop = $(elem).offset().top,
              elemBottom = elemTop + $(elem).height(),

              result = 0;

          if (elemBottom > docViewBottom) {
              result = 1;
          } else if (elemTop < docViewTop) {
              result = -1;
          } 

          return result;
      };
     $el.mouseenter(function (e) {
         timer = setTimeout(function () {
             var $c = $(e.currentTarget);
             var content = $c.data('content');

             var $tt = $('<div class="tooltip fade right"><div class="arrow"></div><h3 class="popover-title" style="display: none;"></h3><div class="popover-content"><article class="default"><h1>Anchorman 2: The Legend Continues</h1><ul><button>£10.99 Buy</button><button>£3.49 Rent</button><p>Hilarious comedy sequel starring Will Ferrell and Steve Carell.</p></article></div></div>').appendTo(e.currentTarget).hide().fadeIn(500);

             $tt.toggleClass('horiz-offscreen', $w.width() < $tt.outerWidth() + $tt.offset().left);


             if (isScrolledIntoView($c) < 0) {
                 $tt.css('top', $w.scrollTop() + 120 - $c.offset().top);
             } else if (isScrolledIntoView($c) > 0) {
                 $tt.css('top', $w.scrollTop() + $w.height() - $c.offset().top - $tt.outerHeight());
             }
         }, delay);
     });