How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

后端 未结 11 1635
刺人心
刺人心 2020-11-27 12:37

I\'m dynamically adding rows to a table using jQuery. The table is inside a div which has overflow:auto thus causing a vertical scroll

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 13:07

    This following works better if you need to scroll to an arbitrary item in the list (rather than always to the bottom):

    function scrollIntoView(element, container) {
      var containerTop = $(container).scrollTop(); 
      var containerBottom = containerTop + $(container).height(); 
      var elemTop = element.offsetTop;
      var elemBottom = elemTop + $(element).height(); 
      if (elemTop < containerTop) {
        $(container).scrollTop(elemTop);
      } else if (elemBottom > containerBottom) {
        $(container).scrollTop(elemBottom - $(container).height());
      }
    }
    

提交回复
热议问题