題目1:如何判斷一個元素是否出現(xiàn)在窗口可視范圍(瀏覽器的上邊緣和下邊緣之間,肉眼可視)。寫一個函數(shù) isVisible實現(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;
}
}
題目2:當窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。每次出現(xiàn)都在控制臺打印 true 。用代碼實現(xiàn)
$(window).on('scroll',function(){
if(isVisible($('p'))){
console.log(true);
}
})
題目3:當窗口滾動時,判斷一個元素是不是出現(xiàn)在窗口可視范圍。在元素第一次出現(xiàn)時在控制臺打印 true,以后再次出現(xiàn)不做任何處理。用代碼實現(xiàn)
var isVis = false; //設(shè)置一個標志位
$(window).on("scroll",function(){
if(!isVis){
isVisible($(".test")); //不可見才進入isVisible函數(shù)
}
else{
return; //一旦標志位為true,那么就不做任何處理
}
})
function isVisible($node){
var winH = $(window).height(),
offsetY = $node.offset().top;
if( (scrollY+winH) > offsetY ){
console.log("true");
isVis = true; //第一次出現(xiàn),設(shè)為true
return true;
}
else{
console.log("false");
return false;
}
}
題目4: 圖片懶加載的原理是什么?
在圖片加載前可以將圖片設(shè)置為一個空白的圖片或者加載中圖片,在圖片可視(offsetH < winH + scrollH)時將圖片通過設(shè)置ajax 或者 data屬性來加載圖片,這樣就能避免加載網(wǎng)頁同時加載大量圖片引起的頁面卡頓情況。
題目5: 實現(xiàn)視頻中的圖片懶加載效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>lazyload</title>
<style>
img{
display: block;
height: 200px;
margin: 5px auto;
}
</style>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
var img =''
for(var i=0;i<20;i++){
img += '' //錯誤1,少加了一個分號,log到懷疑人生
}
$('body').append(img)
lazyLoad();
//每次都是全部加載了,log到。。,原來img沒設(shè)置高度
$(window).scroll(function(){
lazyLoad();
})
function lazyLoad(){
$('img').each(function(){
if(isVisible($(this))&&!isLoaded($(this))){
loadImg($(this))
}
})
}
function isVisible($node){
var scrollTop = $(window).scrollTop()
var windowHeight = $(window).height()
var offsetTop = $node.offset().top
if(offsetTop < windowHeight + scrollTop&&offsetTop > scrollTop){
return true
}
}
function isLoaded($node){
if($node.attr('src') === $node.attr('data-src')){
return true
}
return false
}
function loadImg($node){
$node.attr('src',$node.attr('data-src'))
}
</script>
</body>
</html>