案例是在github上发现的,地址https://github.com/5Iris5/doubanmovie
这里只粘贴一下js的代码,html、css就不粘了
var Helper = {
isToEnd: function($viewport, $content) {
return $viewport.height() + $viewport.scrollTop() + 10 > $content.height()
},
createNode: function(movie) {
var template = `<div class="item">
<a href="#">
<div class="cover">
<img src="" alt="">
</div>
<div class="detail">
<h2></h2>
<div class="extra"><span class="score"></span>分 / <span class="collect"></span>收藏</div>
<div class="extra"><span class="year"></span> / <span class="type"></span></div>
<div class="extra">导演: <span class="director"></span></div>
<div class="extra">主演: <span class="actor"></span></div>
</div>
</a>
</div>`
var $node = $(template);
$node.find('a').attr('href', movie.alt)
$node.find('.cover img').attr('src', movie.images.medium )
$node.find('.detail h2').text(movie.title)
$node.find('.score').text(movie.rating.average )
$node.find('.collect').text(movie.collect_count )
$node.find('.year').text(movie.year)
$node.find('.type').text(movie.genres.join(' / '))
$node.find('.director').text(function() {
var directorsArr = [];
movie.directors.forEach(function(item) {
directorsArr.push(item.name)
})
return directorsArr.join('、')
})
$node.find('.actor').text(function() {
var actorsArr = [];
movie.casts.forEach(function(item) {
actorsArr.push(item.name)
})
return actorsArr.join('、');
})
return $node;
}
}
var Top250 = {
init: function() {
this.$container = $('#top250');
this.$content = $('.container');
this.index = 0;
this.isFinish = false;
this.isLoading = false;
this.bind();
this.start();
},
bind: function() {
var _this = this;
_this.$container.scroll(function() {
if(!_this.isFinish && Helper.isToEnd(_this.$container, _this.$content)) {
_this.start()
}
})
},
start: function() {
var _this = this;
_this.getData(function(data) {
_this.render(data)
})
},
getData: function(callback) {
var _this = this;
if(_this.isLoading) return;
_this.isLoading = true;
_this.$container.find('.loading').show();
$.ajax({
url: 'http://api.douban.com/v2/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a',
data: {
start: _this.index || 0
},
dataType: 'jsonp'
}).done(function(res) {
_this.index += 20;
if(_this.index >= res.total) {
_this.isFinish = true;
}
callback&&callback(res);
}).fail(function() {
console.log('数据错误')
}).always(function() {
_this.isLoading = false;
_this.$container.find('.loading').hide();
})
},
render: function(data) {
var _this = this;
data.subjects.forEach(function(movie) {
_this.$content.append(Helper.createNode(movie))
})
}
}
$(function() {
Top250.init()
})