問答
1.如何判斷一個元素是否出現在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個函數 isVisible實現
<pre>
function isVisible($node){
var scrollH=$(window).scrollTop(),
winH=$(window).height(),
top=$node.offset().top;
if((top > scrollH)&&(top < scrollH + winH )){
return true;
}
else{
return false;
}
}
</pre>
2.當窗口滾動時,判斷一個元素是不是出現在窗口可視范圍。每次出現都在控制臺打印 true 。用代碼實現
<pre>
$(window).on('scroll',function(){
isVisible($node);
});
function isVisible($node){
var scrollH=$(window).scrollTop(),
winH=$(window).height(),
top=$node.offset().top;
if((top > scrollH)&&(top < scrollH + winH )){
console.log('true');
return true;
}
else{
return false;
}
}
</pre>
3.當窗口滾動時,判斷一個元素是不是出現在窗口可視范圍。在元素第一次出現時在控制臺打印 true,以后再次出現不做任何處理。用代碼實現
<pre>
$(window).on('scroll',function(){
if($node.attr('isLoaded')){
return;
}
isVisible($node);
});
function isVisible($node){
var scrollH=$(window).scrollTop(),
winH=$(window).height(),
top=$node.offset().top;
if((top > scrollH)&&(top < scrollH + winH )){
console.log('true');
$node.attr('isLoaded',true);
return true;
}
else{
return false;
}
}
4.圖片懶加載的原理是什么?
懶加載即曝光加載,當圖片曝光在你眼前的時候再去加載,
本質上的作用是解決性能問題。當窗口高度+抽動的距離大
于其到頂部的距離時可見,即winH+scrollTop>offesetTop
防止img為空值的時候瀏覽器出現×,設置img為相同的一個
白圖,當圖片出現在瀏覽器可視范圍內的時候,替換圖片為真正的圖.
版權歸吳秀芳和饑人谷所有,若有轉載,請注明來源