如何判斷一個(gè)元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。
function isVisible($node){
var offsetHeight = $node.offset().top
var windowHeight=$(window).height()
var scrollTop=$(window).scrollTop()
if((offsetHeight>scrollTop) && (offsetHeight<windowHeight+scrollTop)){
return true
}
return false
}
當(dāng)窗口滾動(dòng)時(shí),判斷一個(gè)元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺(tái)打印 true 。用代碼實(shí)現(xiàn)
$(window).on('scroll',function(){
isVisible($('.div1'))
}
})
function isVisible($node){
var offsetHeight = $node.offset().top
var windowHeight = $(window).height()
var scrollTop = $(window).scrollTop()
if((offsetHeight>scrollTop) && (offsetHeight<windowHeight+scrollTop)){
console.log('true')
return true
}
return false
}
}
當(dāng)窗口滾動(dòng)時(shí),判斷一個(gè)元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時(shí)在控制臺(tái)打印 true,以后再次出現(xiàn)不做任何處理。用代碼實(shí)現(xiàn)
var isAppear = false //設(shè)置初始變量為false;
$(window).on('scroll',function() {
function isVisible($node) {
if (!isAppear) { //當(dāng)還未打印過true的時(shí)候執(zhí)行函數(shù)
var offsetHeight = $node.offset().top
var windowHeight = $(window).height()
var scrollTop = $(window).scrollTop()
if( offsetHeight < scrollTop + windowHeight && offsetHeight > scrollTop ){
console.log ('true')
}
isAppear=true //打印過true時(shí),變量設(shè)置為true,后面就不會(huì)執(zhí)行了
}
}
isVisible($('.div1'))
})
圖片懶加載的原理是什么?
將所有圖片的img標(biāo)簽寫入html中
將所有img的src設(shè)置為一張白圖或loading圖片,這樣瀏覽器加載時(shí)只需要發(fā)送一個(gè)請(qǐng)求,因?yàn)閷?duì)于相同內(nèi)容的請(qǐng)求,瀏覽器會(huì)從緩存中獲取數(shù)據(jù)
將img的真實(shí)地址放在data-src自定義屬性當(dāng)中,當(dāng)img出現(xiàn)在視窗時(shí),再將data-src屬性值賦值給src屬性