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

后端 未结 11 1620
刺人心
刺人心 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:12

    I couldn't add a comment to Abhijit Rao's answer above, so I am submitting this as an additional answer.

    I needed to have the table column scroll into view on a wide table, so I added the scroll left features into the function. As someone mentioned, it jumps when it scrolls, but it worked for my purposes.

    function scrollIntoView(element, container) {
      var containerTop = $(container).scrollTop();
      var containerLeft = $(container).scrollLeft();
      var containerBottom = containerTop + $(container).height();
      var containerRight = containerLeft + $(container).width();
    
      var elemTop = element.offsetTop;
      var elemLeft = element.offsetLeft;
      var elemBottom = elemTop + $(element).height();
      var elemRight = elemLeft + $(element).width();
    
      if (elemTop < containerTop) {
        $(container).scrollTop(elemTop);
      } else if (elemBottom > containerBottom) {
        $(container).scrollTop(elemBottom - $(container).height());
      }
    
      if(elemLeft < containerLeft) {
        $(container).scrollLeft(elemLeft);
      } else if(elemRight > containerRight) {
        $(container).scrollLeft(elemRight - $(container).width());
      }
    }
    

提交回复
热议问题