[英]JQuery display element by position - tooltip should change position if parent is offscreen
我的工具提示正确显示,但是如果我向下滚动工具提示,则会偏移刹车。
如果不在屏幕上,如何计算父级的偏移位置?
工具提示应该在屏幕上正确显示! 演示
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();
尝试这个! 你需要用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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.