[Day 28] JS实作练习 - Scroll Blog无限卷动

前言

有注意到每次实作练习的最前面都会有个-观察功能需求项目吗?这是在馒头计画中老师特别强调要拉出来制作的部分,後来看其他技术文或是六角学院课程也会提到这部分的重要性,在开始一个作品前,都要先去了解要制作哪些项目,将它拆解,并大约知道可以用什麽方式来制作,可以快速进入状况、减少紧张感并依据整理出的项目一项项完成,即便中断也能快速衔接上未完成的部分。

课程连结
成品

观察功能需求

1.随着页面的往下卷动,会载入新的资料

  • 一开始页面载入,会呈现5笔资料,卷动往下,会再载入5笔
  • 使用{JSON} Placeholder的资料来串接(运用ajax)
  • 设定卷动位置,并於该位置时,会呈现载入的图示
  • setTimeout来呈现载入的时间与画面

2.网页的各资料是有顺序,资料左上会有编码

  • 利用资料本身的id作为序号
  • 於JS时,带入该变数取值

各项拆解说明

1.API资料来源:

2.使用ajax串接API

  • Async/Await 非同步流程控制-笔记
  • 参考Using async await with jQuery's $.ajaxHow to await the ajax request?,使用jQuery's $.ajax执行async
  • 在try里面,放入一般$.ajax抓取API资料的方式,如url、type、dataType
  • 首先,在连结的部分,我们希望每次抓取5笔资料,呈现1页,所以在外面设置let limit = 5;let page = 1於url中加入该变数
  • 在抓取资料成功时,放入function,并用$.each来执行
    • $.each先传入该资料(data)阵列,其function (index, value)放入索引以及值的内容。
    • 宣告postEl变数,创造名为postdiv=> $('\<div />')
    • 加入postclass
    • 加入html
    • 最後将此变数,放置呈现文章的容器postEl.appendTo('#posts-container');
let limit = 5
let page = 1

async function doAjax() {
  let result;

  try {
    result = await $.ajax({
      url: `https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`,
      type: 'get',
      dataType: 'json',
      success: function (data) {
      
      $.each(data, function (index, value) {
          const postEl = $('<div />').addClass('post').html(`<div class="number">${value.id}</div> <div class="post-info"><h2 class="post-title">${value.title}</h2><p class="post-body">${value.body}</p>
      </div>`)
          //console.log(postEl)
          postEl.appendTo('#posts-container');
          //$('#posts-container').append(postEl)

        });

       
      }
    });

    return result;
  } catch (error) {
    console.error(error);
  }

}

doAjax();

查看是否有成功取得资料:console.log(data);

参考资料:
使用jQuery创造div
https://stackoverflow.com/questions/10402567/jquery-div-vs-div
jQuery.each()

3.Infinite Scroll无限卷动(瀑布流)

  • scrollTop网页右边的卷轴到最上端网页的距离有多少
  • scrollHeight 取得整个没被挡住的高、clientHeight 取得元素的高度(含padding 不含 border)
  • 完整内容高度 (scrollHeight) = 内容顶端与卷轴顶端的距离 (scrollTop) + 卷轴本身高度 (clientHeight) + 内容底端与卷轴底端的距离。

例子:

$(function () {
  $(window).scroll(function () {
    var scrollVal = $(this).scrollTop();
    $("span.qScrollTop").text(scrollVal);
  });
});

if(scrollVal > 500){
  /* 如果滚动的物件卷动 > 500 则触发指定的动作。*/
}

  • 注意:window本身没有scrollTop/Left这个属性,所以window.scrollTop是undefined的
    所以可能要从body、document来取得

本段落语法:

  • 上述说明各视窗高度,在此if判断式中scrollTop + clientHeight >= scrollHeight - 5来计算,当卷轴卷到该位置时,要呈现载入画面
  • 接着根据载入画面函式,来放入载入以及呈现接续画面得设定
    • 使用setTimeout(),在1秒後消除载入图示,接着在300毫秒後,马上换页执行载入新资料
$(window).scroll(function () {
  var scrollTop = $(this).scrollTop();
  var scrollHeight = $('body').prop("scrollHeight");
  //一样 var scrollHeight2 = document.documentElement.scrollHeight;
  var clientHeight = document.documentElement.clientHeight;
  //https://stackoverflow.com/questions/10423759/plain-javascript-to-jquery-clientheight

  // console.log('scrollTop:', scrollTop);
  // console.log('scrollHeight:', scrollHeight);
  // console.log('clientHeight:', clientHeight);


  if (scrollTop + clientHeight >= scrollHeight - 5) {
    //console.log('show up 123')
    showLoading();
  }
})


//显示载入图示,并取得更多串接资料
function showLoading() {
  $('.loader').addClass('show');


  setTimeout(function () {

    $('.loader').removeClass('show');
    setTimeout(function () {
      page++;
      doAjax();
    }, 300);

  }, 1000);  //1秒之後消失

}

参考资料:
[笔记] 计算网页底部位置,当网页达到底部时才产生效果─jQuery
一次搞懂 clientHeight/scrollHeight/scrollTop的区别

4.筛选输入框资料

  • 绑定事件为.keyup指放开键盘的那个刹那,触发该事件
  • 执行的函式内容为:
    • var text取得输入值并转为小写
    • 利用回圈,去搜寻关键字,判断,值转为小写文字的内容是否符合条件
    • -1 :意指条件不符合
    • indexOf() 方法用来判断字串字串变数中是否包含某字串。
//输入框搜寻//https://makitweb.com/jquery-search-text-in-the-element-with-contains-selector/  (=>Loop all .content )
  $('#filter').keyup(function () {

    // 输入值的搜寻
    var text = $('#filter').val().toLowerCase();

    // 隐藏所有资料
    $('.post').hide();

    // 回圈搜寻整个文件
    $('.post').each(function () {

      if ($(this).text().toLowerCase().indexOf("" + text + "") != -1) {
        $(this).closest('.post').show();
      }
    });

参考资料:
比较 keydown, keypress, keyup 的差异
jQuery – Search text in the Element with :contains() Selector
JavaScript String indexOf()


<<:  功能与优化,请选择

>>:  Day 23 资料宝石:【Lab】RDS架构 建立自己的第一台云端资料库 (下)

追求JS小姊姊系列 Day27 -- 从哪里BOM出来的青梅竹马!

前情提要: 工具人揭露了残酷事实,JS有一个青梅竹马的存在! 我: 到底是怎麽样的人物? 工具人们:...

[Day22] Esp32用STA mode + AHT10 - (程序码讲解)

1.前言 这边主要是为解说前几篇关於AHT10的程序码,此次主要讲的部分是loop中的程序码,因为透...

Day23 燃烧溶解文字

燃烧溶解文字 教学原文参考:燃烧溶解文字 这篇文章会介绍在 GIMP 里使用图层合并、遮罩、文字,搭...

[06] [Flask 快速上手笔记] 05. 发送请求与文件上传

在 Flask 里面导入 request 套件包 from flask import request...

[Day28]Hashmat the brave warrior

上一篇介绍了Vito'sfamily,这一题题目讲那麽多,但其实主要是考我们找出中位数,并让每个数都...