Scroll if element is not visible

前端 未结 9 711
旧时难觅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:15

    I think this is the complete answer. An elevator must be able to go both up and down ;)

    function ensureVisible(elementId, top = 0 /* set to "top-nav" Height (if you have)*/) {
      let elem = $('#elementId');
      if (elem) {
        let offset = elem.offset().top - $(window).scrollTop();
        if (offset > window.innerHeight) { // Not in view
          $('html,body').animate({ scrollTop: offset + top }, 1000);
        } else if (offset < top) { // Should go to top
          $('html,body').animate({ scrollTop: $(window).scrollTop() - (top - offset) }, 1000);
        }
      }
    }
    

提交回复
热议问题