1木人、思路
懶加載的思路的關(guān)鍵點是判斷一個元素是否在窗口內(nèi)溯职,如果解決了這個問題弹渔,懶加載的問題就可以迎刃而解,我們通過一張圖來解釋頁面元素在窗口中的距離關(guān)系
這樣通過判定當$(node).offset().top < $s(window).scrollTop() + $(window).height()
的時候元素就出現(xiàn)在了窗口中遏插。
瀑布流的關(guān)鍵點是捂贿,圖片的寬度是固定的,所以可以通過將每一張圖片在窗口中并列排放胳嘲,這個時候就要用到絕對定位厂僧,通過在每張圖片加載過后第一列元素列,找到其中最低的一項了牛,將第二排的第一個元素放在這項的下面颜屠,絕對定位的值是{left: idx * width , top: $el.height}
辰妙,就可與達到瀑布流的排列效果。
2甫窟、代碼
懶加載
var Exposure = {
init: function($target, handler) {
console.log('a')
this.$c = $(window);
this.$target = $target;
this.handler = handler;
this.bind();
this.checkShow();
},
bind: function() {
var me = this,
timer = null,
interval = 100;
$(window).on('scroll', function(e) {
console.log('a')
timer && clearTimeout(timer);
timer = setTimeout(function() {
me.checkShow();
}, interval);
});
},
checkShow: function() {
var me = this;
console.log('a')
this.$target.each(function() {
var $cur = $(this);
if ( me.isShow($cur) ) {
me.handler && me.handler.call(this, this);
$cur.data('loaded', true);
}
});
},
isShow: function($el) {
console.log('a')
var scrollH = this.$c.scrollTop(),
winH = this.$c.height(),
top = $el.offset().top;
if (top < winH + scrollH) {
return true;
} else {
return false;
}
},
hasLoaded: function($el) {
console.log('a')
if ($el.data('loaded')) {
return true;
} else {
return false;
}
}
};
瀑布流
var waterfall = {
//[0,0,0,0]
//[20, 10, 30, 15]
arrColHeight: [],
init: function( $ct ){
this.$ct = $ct;
this.arrColHeight = [];
this.bind();
this.start();
},
bind: function(){
var me = this;
$(window).on('resize', function(){
me.start();
});
},
start: function($nodes){
var me = this;
this.$items = this.$ct.find('.item');
if(this.$items.length ===0) return;
this.itemWidth = this.$items.outerWidth(true);
this.$ct.width('auto');
this.colNum = Math.floor( this.$ct.width() / this.itemWidth );
this.$ct.width(this.itemWidth*this.colNum);
if(this.arrColHeight.length === 0 || !$nodes){
this.arrColHeight = [];
for(var i=0; i<this.colNum; i++){
this.arrColHeight[i] = 0;
}
}
if($nodes){
//console.log(this.arrColHeight.length)
$nodes.each(function(){
var $item = $(this);
$item.find('img').on('load', function(){
me.placeItem( $item );
me.$ct.height( Math.max.apply(null, me.arrColHeight) );
})
});
}else{
this.$items.each(function(){
var $item = $(this);
me.placeItem( $item );
});
me.$ct.height( Math.max.apply(null, me.arrColHeight) );
}
},
placeItem: function( $el ) {
// 1. 鎵懼埌arrColHeight鐨勬渶灝忓€鹼紝寰楀埌鏄鍑犲垪
// 2. 鍏冪礌left鐨勫€兼槸 鍒楁暟*瀹藉害
// 3. 鍏冪礌top鐨勫€兼槸 鏈€灝忓€?
// 4. 鏀劇疆鍏冪礌鐨勪綅緗紝鎶奱rrColHeight瀵瑰簲鐨勫垪鏁扮殑鍊煎姞涓婂綋鍓嶅厓绱犵殑楂樺害
var obj = this.getIndexOfMin(this.arrColHeight),
idx = obj.idx,
min = obj.min;
$el.css({
left: idx * this.itemWidth,
top: min
});
this.arrColHeight[idx] += $el.outerHeight(true);
},
getIndexOfMin: function( arr ){
var min = arr[0],
idx = 0;
for(var i = 1; i< arr.length; i++){
if(min > arr[i]){
min = arr[i];
idx = i;
}
}
return {min: min, idx: idx};
}
}