Scroll if element is not visible

前端 未结 9 722
旧时难觅i
旧时难觅i 2020-12-14 17:57

how to determine, using jquery, if the element is visible on the current page view. I\'d like to add a comment functionality, which works like in facebook, where you only sc

9条回答
  •  醉酒成梦
    2020-12-14 18:25

    No-JQuery version.

    The particular case here is where the scroll container is the body (TBODY, table.body) of a TABLE (scrolling independently of THEAD). But it could be adapted to any situation, some simpler.

    const row = table.body.children[ ... ];
    ...
    
    const bottomOfRow = row.offsetHeight + row.offsetTop ;
    // if the bottom of the row is in the viewport...
    if( bottomOfRow - table.body.scrollTop < table.body.clientHeight ){
        // ... if the top of the row is in the viewport
        if( row.offsetTop - table.body.scrollTop > 0 ){
            console.log( 'row is entirely visible' );
        }
        else if( row.offsetTop - table.body.scrollTop + row.offsetHeight > 0 ){
            console.log( 'row is partly visible at top')
            row.scrollIntoView();
        }
        else {
            console.log( 'top of row out of view above viewport')
            row.scrollIntoView();
        }
    }
    else if( row.offsetTop  - table.body.scrollTop < table.body.clientHeight ){
        console.log( 'row is partly visible at bottom')
        row.scrollIntoView();
    }
    else {
        console.log( 'row is out of view beneath viewport')
        row.scrollIntoView();
    }
    

提交回复
热议问题