題目1:如何判斷一個元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個函數(shù) isVisible實(shí)現(xiàn)
function isVisible($node) {
var scroHeight = $(window).scrollTop();
var windowHeight = $(window).height();
if($node.offset().top<scroHeight+windowHeight && $node.offset().top > scroHeight) {
return true
}
return false
}
題目2:當(dāng)窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺打印 true 。用代碼實(shí)現(xiàn)
$(window).on('scroll',function() {
function isVisible($node) {
var scroHeight = $(window).scrollTop();
var windowHeight = $(window).height();
if($node.offset().top<scroHeight+windowHeight && $node.offset().top > scroHeight) {
console.log('true')
}
})
題目3:當(dāng)窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時在控制臺打印 true,以后再次出現(xiàn)不做任何處理。用代碼實(shí)現(xiàn)
var isAppear = false //設(shè)置初始變量為false;
$(window).on('scroll',function() {
function isVisible($node) {
if (!isAppear) { //當(dāng)還未打印過true的時候執(zhí)行函數(shù)
var scroHeight = $(window).scrollTop()
var windowHeight = $(window).height()
var $nodeTop = $node.offset().top
if( $nodeTop <scroHeight+windowHeight && $nodeTop > scroHeight) {
console.log ('true')
}
isAppear=true //打印過true時,變量設(shè)置為true,后面就不會執(zhí)行了
}
}
isVisible($node)
})
題目4: 圖片懶加載的原理是什么?
當(dāng)訪問一個頁面時,先把元素的圖片路徑設(shè)置為一個相同的路徑,這樣只用請求一次,當(dāng)元素進(jìn)入窗口可視區(qū)域時,再將元素圖片設(shè)置為真正的圖片路徑,讓圖片顯示出來。