如何判斷一個元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個函數(shù) isVisible實現(xiàn)
function isVisible($node){
var windowHeight = $(window).height(), //窗口的高度
scrollTop = $(window).scrollTop(), //滾動距離頂點的距離
offsetTop = $node.offset().top, //傳遞的參數(shù)距離頂點的距離
nodeHeight = $node.height(); //節(jié)點的自身高度
if(windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight){
return true;
}else{
return false;
}
}
當窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺打印 true 。用代碼實現(xiàn)
<p id="hello">hello</p>
$(window).on('scroll',function(){
if(isVisible($('#hello'))){
console.log(true)
}
})
function isVisible($node){
var windowHeight = $(window).height(), //窗口的高度
scrollTop = $(window).scrollTop(), //滾動距離頂點的距離
offsetTop = $node.offset().top, //傳遞的參數(shù)距離頂點的距離
nodeHeight = $node.height(); //節(jié)點的自身高度
if(windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight){
return true;
}else{
return false;
}
}
當窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時在控制臺打印 true,以后再次出現(xiàn)不做任何處理。用代碼實現(xiàn)
<p id="hello">hello</p>
$(window).on('scroll',function(){
if(isVisible($('#hello')) && !$('#hello').hasClass('show')){
$('#hello').addClass('show') //當出現(xiàn)過一次后加個標簽
console.log(true)
}
})
function isVisible($node){
var windowHeight = $(window).height(), //窗口的高度
scrollTop = $(window).scrollTop(), //滾動距離頂點的距離
offsetTop = $node.offset().top, //傳遞的參數(shù)距離頂點的距離
nodeHeight = $node.height(); //節(jié)點的自身高度
if(windowHeight + scrollTop > offsetTop && scrollTop < offsetTop + nodeHeight){
return true;
}else{
return false;
}
}
圖片懶加載的原理是什么?
對于圖片過多的頁面,為了加速頁面加載速度,所以很多時候我們需要將頁面內(nèi)未出現(xiàn)在可視區(qū)域內(nèi)的圖片先不做加載, 等到滾動到可視區(qū)域后再去加載。這樣子對于頁面加載性能上會有很大的提升,也提高了用戶體驗。
實現(xiàn)原理:
- 當窗口滾動時
- 判斷圖片是否出現(xiàn)在可視區(qū)域
- 若出現(xiàn)了就展示圖片,并把展示的圖片加上標記以防之后重復判斷