題目1:如何判斷一個元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個函數(shù) isVisible實現(xiàn)
function isVisible($node){
var scrollHeight = $(window).scrollTop();
var showHeight = $(window).height();
var offset = $node.offset().top;
if(offset > scrollHeight && offset < showHeight + scrollHeight){
return true;
}
return false;
}
題目2:當(dāng)窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺打印 true 。用代碼實現(xiàn)
$(window).on('scroll', function(){
var $node = $('.node')
if (isVisible($node)){
console.log(isVisible($node))
}
})
function isVisible($node){
var scrollHeight = $(window).scrollTop();
var showHeight = $(window).height();
var offset = $node.offset().top;
if(offset > scrollHeight && offset < showHeight + scrollHeight){
return true;
}
return false;
}
題目3:當(dāng)窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時在控制臺打印 true,以后再次出現(xiàn)不做任何處理。用代碼實現(xiàn)
$(window).on('scroll', function(){
var $node = $('.node');
var lock;
if (isVisible($node) && !$node.attr('lock')){
console.log(isVisible($node));
$node.attr('lock', true);
}
})
function isVisible($node){
var scrollHeight = $(window).scrollTop();
var showHeight = $(window).height();
var offset = $node.offset().top;
if(offset > scrollHeight && offset < showHeight + scrollHeight){
return true;
}
return false;
}
題目4: 圖片懶加載的原理是什么?
作用:監(jiān)聽事件發(fā)生,再進行下載圖片,這樣可以提高性能(放置一次性加載多張圖片而產(chǎn)生卡頓),也能幫用戶省流量
原理:先創(chuàng)建一個新的標(biāo)簽(data-src)放置真是圖片地址,在img節(jié)點中的src標(biāo)簽放置同一張無意義(空白)圖片,待事件發(fā)生(滾動事件)時,把data-src中的圖片地址放置到src中,讓瀏覽器加載。