0
所有圖像均由ajax負載。有時它是完美的,但通常它不工作正確 - 看看screen,所有的圖像相互重疊。我的錯在哪裏?我會重構這段代碼,當我解決這個問題:)。後端:Ruby on Rails。砌體ajax負載無法正常工作
JS:
$(document).ready(function() {
(function() {
$.ajax({
url: '/photos?page=' + 1,
type: 'get',
dataType: 'script',
success: function(data) {
var $container = $('#photo-container');
var items = JSON.parse(data);
items.forEach(function(item) {
var img = $('<img src="' + item.image.url + '" />');
var elem = $('<div class="grid__item"><img src="' + item.image.url + '" /></div>');
$container.append(elem);
});
initMasonry();
initInfiniteScroll();
}
});
}());
});
function initMasonry() {
var $container = $('#photo-container');
$container.masonry({
gutter: 20,
itemSelector: '.grid__item',
columnWidth: 300
});
}
function initInfiniteScroll() {
var page = 1,
loading = false;
function nearBottomOfPage() {
return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
}
$(window).scroll(function(){
if (loading) {
return;
}
if(nearBottomOfPage()) {
loading=true;
page++;
$.ajax({
url: '/photos?page=' + page,
type: 'get',
dataType: 'script',
success: function(data) {
var $container = $('#photo-container');
var arr = JSON.parse(data);
arr.forEach(function(item) {
var img = $('<img src="' + item.image.url + '" />');
var elem = $('<div class="grid__item"><img src="' + item.image.url + '" /></div>');
$container.imagesLoaded(function() {
$container.append(elem).masonry('appended', elem, true).masonry('reloadItems');
});
});
loading=false;
}
});
}
});
}