函数computeVisibleHeight($ t)计算元素的可见部分。可见部分是指在窗口中可见的部分,现在我不确定如何将该函数转移到箭头div并使箭头具有元素的可见部分的高度。
我评论了mouseleave功能,只适用于第二次悬停!!!!不知道为什么。 请帮忙。
演示:http://fiddle.jshell.net/ggvWR/7/
JS:
$.fn.tooltip = function () {
var $el = $(this);
var $w = $(window);
var timer;
var delay = 500;
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;
};
function computeVisibleHeight($t) {
var top = $t.position().top;
var windowHeight = $(window).height();
var scrollTop = $(window).scrollTop();
var height = $t.height();
if (top < scrollTop && height - scrollTop >= windowHeight) {
// first case: the top and the bottom of the element is outside of the window
return windowHeight;
} else if (top < scrollTop) {
// second: the top is outside of the viewport but the bottom is visible
return height - (scrollTop - top);
} else if (top > scrollTop && top + height < windowHeight) {
// the whole element is visible
return height;
} else {
// the top is visible but the bottom is outside of the viewport
return windowHeight - (top - scrollTop);
}
}
$el.mouseenter(function (e) {
timer = setTimeout(function () {
var $c = $(e.currentTarget);
var content = $c.data('content');
var $ar = $('.fix-arrow');
var $h = computeVisibleHeight(($c));
var $tt = $('<div class="tooltip right"><div class="arrow"><div class="fix-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('left', $w.width() < $tt.outerWidth() + $tt.offset().left);
if (computeVisibleHeight(($c)) > 207) {
$ar.css('height', $h - 63);
}
if (computeVisibleHeight(($c)) < 207) {
$ar.css('height', $h);
}
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);
});
$el.mouseleave(function (e) {
// $('.tooltip', e.currentTarget).fadeOut(500, function () {
// $(this).remove();
//});
clearTimeout(timer);
});
};
$('.item').tooltip();