Use native js to achieve pull-up loading and pull-down refresh

Pull up to load, pull down to refresh

foreword

  • Pull-to-refresh and pull-to-load interactions usually appear on mobile terminals, which are essentially equivalent to pagination in PC webpages, but the interaction forms are different
  • There are many excellent solutions in the open source community, such as iscroll, better-scroll, pulltorefresh.jsetc.
  • Use the native method to achieve pull-up loading and pull-down refresh, which helps to better understand and use third-party libraries

pull up load

  • The essence of pull-up loading is the action when the page bottoms out or is about to bottom out
  • To judge the bottom, we need to understand the following properties
    • scrollTop: The distance between the height of the scrolling window and the top of the window, it will change continuously with the scrolling, the initial value is 0, it is a changing value
    • scrollHeight: Indicates the total height of all elements of the body (including the padding of the body itself)
    • clientHeight: It is a fixed value, indicating the height of the visible area of ​​the screen
    • When clientHeight= scrollHeightthe page will not scroll
    • Bottom formula: clientHeight(screen visible area height)+ scrollTop(scroll height)>= scrollHeight(total content height)

Simple implementation

let clientHeight  = document.documentElement.clientHeight; //浏览器高度
let scrollHeight = document.body.scrollHeight;
let scrollTop = document.documentElement.scrollTop;
 
let distance = 50;  //距离视窗还用50的时候,开始触发;

if ((scrollTop + clientHeight) >= (scrollHeight - distance)) {
    console.log("开始加载数据");
}

Pull down to refresh

Pull-down refresh is essentially an action that needs to be triggered when the user pulls down when the page itself is placed at the top

  • Listen to the native touchstart event and record the value of its initial position, e.touches[0].pageY
  • Listen to the native touchmove event, record and calculate the difference between the current sliding position value and the initial position value, greater than 0 means pulling down, use the translateY attribute of css3 to make the element follow the gesture to slide down the corresponding difference, and also set a permission sliding maximum
  • Listen to the original touchend event. If the element slides to the maximum value at this time, the callback will be triggered, and translateY will be reset to 0, and the element will slide to the initial position.

Guess you like

Origin blog.csdn.net/jyl919221lc/article/details/128835399