簡體   English   中英

滾動到特定DOM時如何加載內容?

[英]How can I load something when I scroll to specific DOM?

我想在滾動<div class="loadChart">時加載chart.html ,並在第一次加載它。

var loadChart = $('.loadChart').offset().top;
console.log(loadChart); //loadChart top is 1532

我使用setTimeout進行控制,但是仍然有麻煩。 這是我的代碼↓

var timer;
window.onscroll = function(){
  var scrollPos = $(document).scrollTop(); 
  if(scrollPos>=1532){
            window.clearTimeout(timer);
            timer = window.setTimeout(function() {
                $('.loadChart').load('chart.html');
            }, 1000);
   }
}

我該如何使用jQuery和JavaScript?

您要做的是將窗口高度添加到滾動位置,以便div從底部進入視口后立即加載內容。 否則,內容只會在您滾動到足以使其接觸視口頂部時加載。

您也不需要setTimeout除非出於性能原因要實現某種頻率上限(但這不是您實現的方式)。

然后,確保在加載內容后取消設置onscroll回調。 (或者,如果您需要其他內容,請設置數據屬性或變量(如果內容已加載),然后檢查該變量,以查看是否必須觸發load()

 var loadChart = $('.loadChart'), loadChartTop = $('.loadChart').offset().top; window.onscroll = function(){ var scrollPos = $(document).scrollTop(); if(scrollPos + window.innerHeight >=loadChartTop){ console.log("would load now!"); loadChart.load('chart.html'); // remove onscroll callback window.onscroll = null; } } 
 .loadChart { background: red; text-align: center; color: #ffffff; height: 500px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> other content<br> <div class="loadChart"> chart will be here! </div> 

首先,為什么要使用計時器? 其次,不要將固定像素值用作偏移頂部。 這可能會改變,並會導致您的代碼無法正常工作。 使用變量

請參見下面的代碼段

 var offTop = $('.loadChart').offset().top $(window).on("scroll",function() { var scrollPos = $(this).scrollTop() if ( scrollPos > offTop) { $(".loadChart").load("yourpagehere") } }) 
 .loadChart { height:200px; margin-top:100px; background:red; } .bottom { height:800px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="loadChart"> Load Chart here </div> <div class="bottom"> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM