我正在为我的tumblr页面编写一个小jQuery脚本,它模拟无限滚动,通过jQuery.get()加载站点下几页中我想要的内容(这是一个tumblr站点,所以分页是可以的)。
我知道有一些无限的滚动插件,但我试着不为我工作,而且,还相当胖。我不需要那些有趣的东西。脚本加载我想要的新元素,是的,但问题是每次从两个页面加载内容。而且,很明显,它应该只加载一个页面内容。
jQuery是:
$(document).ready(function() {
"use strict";
var nextPage = 2;
var totalPages = {TotalPages};
var url = '/page/'; // base url
$(document).on('scroll', function() {
if (nextPage <= totalPages) { // if exist new pages
if ($(window).scrollTop()== $(document).height() - $(window).height()) { // when reach the page bottom
$.get(url + nextPage, function(data){ // get the next page
$(data).find(".post").appendTo(".posts"); // filter content we want and append it to the actual page element
picturefill(); // reload picturefill,making the new images responsive
});
nextPage++; // increment nextpage counter
};
} else { // exit if no more pages
return;
}
});
}); 它加载的内容是:
<div class="posts">
<article class="photo-container post" id="{PostID}" data-reblog="{ReblogURL}">
<div class=" picturefill" data-picture data-alt="" data-class="photo">
<div class="picturefill" data-src="{PhotoURL-HighRes}" ></div>
<div class="picturefill" data-src="{PhotoURL-500}" data-media="(max-width: 568px)"></div>
<div class="picturefill" data-src="{PhotoURL-250}" data-media="(max-width: 250px)"></div>
<img alt="" class="photo" src="http://img.jpg"> <!-- generated by picturefill -->
<noscript><img class="photo" src="{PhotoURL-HighRes}" alt=""></noscript>
</div>
<!-- MORE CODE -->
</article>
我使用皮图来处理响应性图像,而且效果很好。有谁有主意吗?谢谢。
发布于 2015-02-08 20:18:28
(在问题编辑中回答。转换成社区wiki的答案。见什么是适当的行动,当一个问题的答案被添加到问题本身? )
“任择议定书”写道:
我使用一个控制变量
lastLoadingPos解决了我的问题,它存储脚本插入页面内容的最后一个位置(相对于文档)。如果该位置不改变,则不会执行插入操作。这是因为多个内容插入之所以发生,是因为脚本检测到在同一位置超过一次到达页面底部。是的,这解决了问题,但我认为这不优雅,不是正确的解决办法。只是个解决办法。如果有人知道,它会受到欢迎:D 我的解决方案是(当然,我仍然需要添加一两件事情): $(.ready)(函数(){“使用严格”;var nextPage = 2;var lastLoadingPos = 0;//存储最后插入位置(与文档相关的) var totalPages = {TotalPages};var = '/page/';//基url $(文档).on(‘滚动’,函数(){ if (nextPage <= totalPages) ){ //如果存在新的var页面顶部=$(窗口).scrollTop();如果((lastLoadingPos != top) & (top== $(document).height() -$(Window).height()){ //当当前底部位置第一次到达lastLoadingPos = top;//新的最后插入位置$.get(url + nextPage,函数(数据)){ //获取下一页$(数据).find(“.post”).appendTo(“.posts”);// filter需要内容微微填充();//重新加载图片填充,使新图像响应nextPage++;//增量下一页计数器};}{ //退出(如果没有更多的页面返回;} });
https://stackoverflow.com/questions/14838154
复制相似问题