把你的代碼包裝在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();
});
UPDATE
不知道,如果我理解正確你的要求。註釋掉函數定義有幫助嗎?我也沒有看到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");
});
});
這個工程,但我有mousover功能,做某些事情,如果我把滾動功能內distanceBottom變量不再可訪問。另一方面,我不能使用滾動函數來包裝所有東西,因爲每當滾動時它都會觸發。你有什麼建議嗎? –
我想你的意思是「distanceBottom裏面的滾動功能」,而不是「distanceBottom裏面的滾動功能」。從window.scroll函數(全局)聲明distanceBottom變量,並且它可以從任何地方訪問。 – Tariqulazam
我已經添加了整個代碼。我想要實現的是計算div和瀏覽器底部的距離,只要該div有鼠標移動即可。上面的代碼做了所有的事情,但只要pade滾動,距離就需要更新... –