Detect Document Height Change

后端 未结 8 972
独厮守ぢ
独厮守ぢ 2020-12-04 10:07

I\'m trying to detect when my document height changes. Once it does, I need to run a few functions to help organize my page layout.

I\'m not looking fo

相关标签:
8条回答
  • 2020-12-04 11:06

    I'm using @vsync's solution, like this. I'm using it for automatic scroll on a page like twitter.

    const scrollInterval = (timeInterval, retry, cb) => {
        let tmpHeight = 0;
        const myInterval = setInterval(() => {
            console.log('interval');
            if (retry++ > 3) {
                clearInterval(this);
            }
            const change = document.body.clientHeight - tmpHeight;
            tmpHeight = document.body.clientHeight;
            if (change > 0) {
                cb(change, (retry * timeInterval));
                scrollBy(0, 10000);
            }
            retry = 0;
        }, timeInterval);
        return myInterval;
    };
    
    const onBodyChange = (change, timeout) => {
        console.log(`document.body.clientHeight, changed: ${change}, after: ${timeout}`);
    }
    
    const createdInterval = scrollInterval(500, 3, onBodyChange);
    
    // stop the scroller on some event
    setTimeout(() => {
        clearInterval(createdInterval);
    }, 10000);
    

    You can also add a minimum change, and a lot of other things... But this is working for me

    0 讨论(0)
  • 2020-12-04 11:09

    As mentioned by vsync there is no event but you can use a timer or attach the handler somewhere else:

    // get the height
    var refreshDocHeight = function(){
        var h = $(document).height();
        $('#result').html("Document height: " + h);
    };
    
    // update the height every 200ms
    window.setInterval(refreshDocHeight, 200);
    
    // or attach the handler to all events which are able to change 
    // the document height, for example
    $('div').keyup(refreshDocHeight);
    

    Find the jsfiddle here.

    0 讨论(0)
提交回复
热议问题