如何判斷一個(gè)元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫(xiě)一個(gè)函數(shù) isVisible實(shí)現(xiàn)
function isVisible($node) {
var windowHeight = $(window).height(),
scrollTop = $(window).scrollTop(),
offsetTop = $node.offset().top,
nodeHeight = $node.outerHeight(true);
if (windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight) {
return true;
} else {
return false;
}
}
當(dāng)窗口滾動(dòng)時(shí),判斷一個(gè)元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺(tái)打印 true 。用代碼實(shí)現(xiàn)
$(window).scroll(function(){
if(isShow($('#hello'))){
console.log(true);
}else{
console.log(false);
}
})
function isShow($node) {
var windowHeight = $(window).height(),
scrollTop = $(window).scrollTop(),
offsetTop = $node.offset().top,
nodeHeight = $node.outerHeight(true);
if (windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight) {
return true;
} else {
return false;
}
}
當(dāng)窗口滾動(dòng)時(shí),判斷一個(gè)元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時(shí)在控制臺(tái)打印 true,以后再次出現(xiàn)不做任何處理。用代碼實(shí)現(xiàn)
$(window).scroll(function () {
if ($('#hello').not('.load').length === 1 && isVisible($('#hello'))) {
console.log(true);
$('#hello').addClass('load');
} else {
console.log(false);
}
})
function isVisible($node) {
var windowHeight = $(window).height(),
scrollTop = $(window).scrollTop(),
offsetTop = $node.offset().top,
nodeHeight = $node.outerHeight(true);
if (windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight) {
return true;
} else {
return false;
}
}
圖片懶加載的原理是什么?
- 在頁(yè)面載入的時(shí)候?qū)㈨?yè)面上的圖片地址指向一張圖片,等圖片進(jìn)入窗口可視區(qū)域時(shí),把在自定義屬性中的真實(shí)圖片地址放入src屬性中,實(shí)現(xiàn)當(dāng)前區(qū)域加載。
實(shí)現(xiàn)視頻中的圖片懶加載效果
實(shí)現(xiàn)視頻中的新聞懶加載效果
test.gif