将代码包装在 window.scroll 事件中,每次滚动文档时都会调用它。如果将它放在文档 onload 事件中,它会被调用一次,因此之后不会更新。
$(window).scroll(function () {
var the_height = $(window).height(); // viewport height
var activeimage = $(this); // div element
distanceBottom = the_height - activeimage.offset().top + activeimage.height();
});
更新
不确定,如果我正确理解您的要求。注释掉函数定义有帮助吗?我也没有看到 distanceBottom 变量的任何用法。
$(document).ready(function () {
$('div.thumbnail-item').mouseenter(function(e) {
contents = $(this).find('.tooltip').find('.invisible').html();
tooltip = $(this).find('.tooltip').find('img');
wholetooltip = $(this).find('.tooltip');
var activeimage = $(this); // div element
tooltip.attr('src', contents);
//$(window).scroll(function () {
var the_height = $(window).height(); // viewport height
distanceBottom = the_height - activeimage.offset().top + activeimage.height();
//});
if (tooltip[0].complete) { // if image already loaded
tooltipWidth = wholetooltip.width();
tooltipHeight = wholetooltip.height();
imgwidth = activeimage.width();
imgheight = activeimage.height();
test = 0 - tooltipHeight + imgheight; // will position nice without gray border
activeimage.css('z-index','999')
.children("div.tooltip")
.css({'top': test,'left': imgwidth + 30,'display':'block'});
} else { // if image not loaded
tooltip.load(function() {
imgwidth = activeimage.width();
imgheight = activeimage.height();
test = activeimage.offset().top - activeimage.offset().top - imgheight;
activeimage.css('z-index','999')
.children("div.tooltip")
.css({'top': test,'left': imgwidth + 30,'display':'block'});
tooltip.css({
'border-color': 'red',
'border-width': '5px'
});
});
}
}).mouseleave(function() {
// Reset the z-index and hide the image tooltip
$(this).css('z-index','10')
.children("div.tooltip")
.animate({"opacity": "hide"}, "fast");
});
});