2012-10-17 66 views
0

如何使div元素和瀏覽器自動更新本身的距離?滾動時更新元素和窗口之間的距離

這是我的計算從元素到窗口底部的距離的代碼部分。它工作正常,儘管用戶滾動時值不更新。讓我們假設有幾個塊,我需要知道這些塊是否靠近窗口邊緣。正如我前面提到的,這將計算距離onload,但如果用戶滾動頁面,我需要它來更新這些值。有任何想法嗎?

var the_height = $(window).height(); // viewport height 
var activeimage = $(this); // div element 
distanceBottom = the_height - activeimage.offset().top + activeimage.height(); 

jsFiddle

而現在,因爲小提琴也是在這裏,我需要距離值是因爲我想確保工具提示是可見的區域內。我最初的想法是,如果拇指真的接近邊緣,請將工具提示位置放在拇指上方。那就是需要距離的地方

回答

3

把你的代碼包裝在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"); 
    }); 

}); 
+0

這個工程,但我有mousover功能,做某些事情,如果我把滾動功能內distanceBottom變量不再可訪問。另一方面,我不能使用滾動函數來包裝所有東西,因爲每當滾動時它都會觸發。你有什麼建議嗎? –

+0

我想你的意思是「distanceBottom裏面的滾動功能」,而不是「distanceBottom裏面的滾動功能」。從window.scroll函數(全局)聲明distanceBottom變量,並且它可以從任何地方訪問。 – Tariqulazam

+0

我已經添加了整個代碼。我想要實現的是計算div和瀏覽器底部的距離,只要該div有鼠標移動即可。上面的代碼做了所有的事情,但只要pade滾動,距離就需要更新... –

相關問題