1 如何判斷一個元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個函數(shù) isVisible實現(xiàn)
function isVisible($node) {
var winH = $(window).height(),
scrollH = $(window).scrollTop(),
top = $node.offset().top
if(top > scrollH && top < scrollH + winH){
return true
}else {
return false
}
}
2 當窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺打印 true 。用代碼實現(xiàn)
function isVisible($node) {
var winH = $(window).height(),
scrollH = $(window).scrollTop(),
top = $node.offset().top
if(top > scrollH && top < scrollH + winH){
return true
}else {
return false
}
}
$(window).on('scroll',function () {
if(isVisible($node)){
console.log('true')
}
})
3 當窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時在控制臺打印 true,以后再次出現(xiàn)不做任何處理。用代碼實現(xiàn)
function isVisible($node) {
var winH = $(window).height(),
scrollH = $(window).scrollTop(),
top = $node.offset().top
if(top > scrollH && top < scrollH + winH){
return true
}else {
return false
}
}
$(window).on('scroll',function () {
if(isVisible($node) && !($node.data('hasLoad'))){
$node.data('hasLoad', true)
console.log('true')
}
})
4 懶加載原理
1.首先把圖片的src屬性設置為設置為空,或者放入一張空白圖片,把圖片真實地址放入自定義屬性中。
2.當滾動頁面時,判斷img標簽是否出現(xiàn)在視窗內。當img出現(xiàn)在視窗內進行判斷圖片是否已經加載,若加載過則無需處理,若未加載過則進行加載。