如何判斷一個元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個函數(shù) isVisible實(shí)現(xiàn)
function isVisible($node){
var scrollHeight=$(window).scrollTop();//滾動條的高度
var windowHeight=$(window).height();//瀏覽器窗口的高度
var offsetHeight=$($node).offset().top;//元素到頁面的頂部的偏移
if(offsetHeight<scrollHeight+windowHeight&&offsetHeight>scrollHeight){
return true;
}else {
return false;
}
}
當(dāng)窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺打印 true 。用代碼實(shí)現(xiàn)
$(window).on('scroll',function($node){
var scrollHeight=$(window).scrollTop();
var windowHeight=$(window).height();
var offsetHeight=$($node).offset().top;//$node是傳入的元素
if(offsetHeight<scrollHeight+windowHeight&&offsetHeight>scrollHeight) {
console.log("true");
}
})
當(dāng)窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時在控制臺打印 true,以后再次出現(xiàn)不做任何處理。用代碼實(shí)現(xiàn)
function isLoad($node){
$(window).on('scroll',function($node){
var scrollHeight=$(window).scrollTop();
var windowHeight=$(window).height();
var offsetHeight=$($node).offset().top;
if(offsetHeight<scrollHeight+windowHeight&&offsetHeight>scrollHeight){
if($($node).attr('src')===$($node).attr('data-src')) {
return true;
}else {
$($node).attr('src',$($node).attr('data-src'));
console.log('true');
}
}
});
}
圖片懶加載的原理是什么?
如果網(wǎng)頁的圖片過多,全部加載的時候,會很慢,用戶體驗(yàn)不好,為了使網(wǎng)頁加載速度更快,我們就先加載出現(xiàn)在瀏覽器窗口的圖片,不在窗口范圍內(nèi)的圖片,等滾動到的時候再加載,這樣頁面的加載速度會提高很多。
實(shí)現(xiàn)原理是這樣的,把圖片的真實(shí)地址放到圖片的一個自定義屬性上,一般是data-src,圖片的src放的是指向一張空白圖片的地址,當(dāng)頁面加載時判斷圖片位置是否出現(xiàn)在了可視區(qū)域內(nèi)。如果出現(xiàn)在可視區(qū)域了那么就把data-src的真實(shí)地址賦值給src,加載之后的圖片不再做處理。