Pull-down refresh idea:

1. Listen for the native TouchStart event and record its initial position value;

2. Monitor the original Touchmove event, record and calculate the difference between the current sliding position value and the initial position value on the Y-axis as the sliding distance, and use the translateY attribute of CSS3 to make the element follow the gesture to slide down the corresponding difference; At the same time, different text information is displayed according to the sliding distance, such as “drop-down refresh “->” release immediate update “;

3. Listen to the original Touchend event. If the sliding distance is less than the set minimum moving distance, the loading will be cancelled; otherwise, the loading operation will be carried out; At the same time, resetting translateY to 0 returns the element to its original position.


Pull-up loading idea:

Pull-up loading is usually triggered when the page scrolls to the bottom, or optionally triggered when the page scrolls to a certain position.

Take the example of rolling to a certain position. The implementation principle is to obtain the scrollTop value of the current scroll bar, the height value of the current visual range clientHeight and the total height of the document scrollHeight. When scrollHeight – (scrollTop+clientHeight) is less than a certain value, the data is loaded and added to the page.


The pull-up refresh is achieved mainly by the three stages of touch events, with the help of CSS3 animation effects;

Pull-down loading mainly depends on the onScroll event of the page. It should be noted that function throttling may be considered when the page is scrolling.


The source code

Home page index. HTML:


      
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Pull-up refresh pull-down load</title>
    <style>
        html.body {
            padding: 0;
            margin: 0;
        }
        
        ul li {
            list-style: none;
        }
        
        main p {
            text-align: center;
        }
        
        .nav {
            background-color: #2196F3;
            color: #fff;
            height: 35px;
            text-align: center;
            line-height: 35px;
            margin: 0;
            padding: 0;
        }
        
        #pullUpText.#pullDownText {
            color: #03a9f4
        }
    </style>
    <script>
    </script>
</head>

<body>

    <header>
        <p class="nav">Pull-up refresh pull-down load</p>
    </header>
    <main id="refreshContainer">
        <p id="pullUpText"></p>
        <ul id="refreshContent"></ul>
        <p id="pullDownText">loading</p>
    </main>

    <script src="./generateData.js"></script>
    <script src="./pullUp.js"></script>
    <script src="./pullDown.js"></script>


    <script>
        let refreshContainer = document.getElementById('refreshContent')
        let pullDownText = document.getElementById('pullDownText')


        // Drop down to refresh the function executed
        function refresh() {
            let initData = generateRandomDataArray(50)
            let fragment = dataToDocumentFragment(initData)
            refreshContainer.innerHTML = ' '
            refreshContainer.appendChild(fragment)
        }
        refresh();


        // Pull-up loads the function executed
        function pullUpLoad() {
            let loadData = loadDataFunc(10)
            if (loadData.length === 0) {
                pullDownText.textContent = 'No more data'
                return;
            }
            let fragment = dataToDocumentFragment(loadData)
            refreshContainer.appendChild(fragment)
        }

        // Convert data to HTML tags
        function dataToDocumentFragment(data) {
            let fragment = document.createDocumentFragment()
            data.forEach(d= > {
                let li = document.createElement('li')
                li.textContent = d;
                fragment.appendChild(li)
            })
            return fragment;
        }
    </script>



</body>

</html>

Copy the code


Generatedata.js that generates the data:

function generateRandomDataArray(length) {
    let array = []
    for (let i = 0; i < length; i++) {
        let data = Math.random().toString().slice(2.6)
        array.push(data)
    }
    return array;
}


let loadDataFunc = (function() {
    let id = 0;
    return function(length) {
        let array = []
        for (let i = 0; i < length; i++) {
            array.push(id++)
        }
        return array;
    }
})()Copy the code



Pulldown.js for the dropdown refresh feature:

/** * drop down refresh */


var min_move_distance = 50; // Minimum moving distance. If the moving distance is less than this value, the load is cancelled
var showPullUpTextDistance = 30

var refreshContainerEle = document.getElementById('refreshContainer'),
    pullUpTextEle = document.getElementById('pullUpText'),
    startPos = 0,
    transitionHeight = 0;

refreshContainerEle.addEventListener('touchstart'.function(e) {
    // console.log(' initial position: ', e.touches[0].pagey); // console.log(' initial position: ', e.touches[0].pagey);
    startPos = e.touches[0].pageY;
    refreshContainerEle.style.position = 'relative';
    refreshContainerEle.style.transition = 'transform 0s';
}, false);


refreshContainerEle.addEventListener('touchmove'.function(e) {
    // console.log(' current position: ', e.touches[0].pagey); // console.log(' current position: ', e.touches[0].pagey);
    transitionHeight = e.touches[0].pageY - startPos;

    if (transitionHeight > showPullUpTextDistance) {

        pullUpTextEle.innerText = 'Pull refresh';

        if (transitionHeight > min_move_distance) {
            pullUpTextEle.innerText = 'Release update Now';
        }

        refreshContainerEle.style.transform = 'translateY(' + transitionHeight + 'px)';
        pullUpTextEle.style.lineHeight = transitionHeight + 'px'; }},false);



refreshContainerEle.addEventListener('touchend'.function(e) {
    refreshContainerEle.style.transition = 'transform s linear 0.3 0.5 s';
    refreshContainerEle.style.transform = 'translateY(0px)';

    setTimeout((a)= > {
        pullUpTextEle.style.lineHeight = "normal";
    }, 800)

    if (transitionHeight > min_move_distance) {
        pullUpTextEle.innerText = 'In update... ';

        console.log("In update");


        // The update is complete
        setTimeout((a)= > {
            refresh()
            pullUpTextEle.innerText = ' ';
        }, 1000)}else {
        pullUpTextEle.innerText = ' ' // Cancel the update;}},false);
Copy the code




Pullup.js for pull-up loading

/** * pull up load */

var preloadDistance = 100; // How many pixels ahead to start loading


// Get the current scroll bar position
function getScrollTop() {
    var scrollTop = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    } else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    return scrollTop;
}

// Get the height of the current viewable range
function getClientHeight() {
    var clientHeight = 0;
    if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
    } else {
        clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
    }
    return clientHeight;
}

// Get the full height of the document
function getScrollHeight() {
    return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}


var pullUpTextEle = document.getElementById('pullDownText'),
    refreshContainerEle = document.getElementById('refreshContainer');


// throttling function
var throttle = function(method, context) {
    clearTimeout(method.timeId);
    method.timeId = setTimeout(function() {
        console.log("Loading");
        method.call(context);
    }, 300);
}


// Get the data
function fetchData() {
    setTimeout(function() {
        pullUpLoad()
    }, 1000);
}


window.onscroll = function() {
    if (getScrollHeight() - (getScrollTop() + getClientHeight()) < preloadDistance) {

        pullUpTextEle.innerText = 'Loading... '; throttle(fetchData); }};Copy the code