scrollinToView() 将元素置于底部。如何将元素滚动到顶部

scrollToView() brings the element at the bottom. How to scroll element to the TOP

我在列表中有很多元素 (table)。我想自动滚动到一个特定元素。

使用 table.getRowElement(50).scrollIntoView(); 将列表滚动到所需的元素,但刚好足以在 scrollPanel 中可见,即在底部。

如何将元素滚动到顶部?

您只需要稍微修改一下 DOMImpl.class 中的 scrollIntoView 方法,省去高度。

public native void scrollIntoView(Element elem) /*-{
    var left = elem.offsetLeft, top = elem.offsetTop;
    var width = elem.offsetWidth, height = elem.offsetHeight;
    if (elem.parentNode != elem.offsetParent) {
        left -= elem.parentNode.offsetLeft;
        top -= elem.parentNode.offsetTop;
    }
    var cur = elem.parentNode;
    while (cur && (cur.nodeType == 1)) {
      if (left < cur.scrollLeft) {
        cur.scrollLeft = left;
      }
      if (left + width > cur.scrollLeft + cur.clientWidth) {
        cur.scrollLeft = (left + width) - cur.clientWidth;
      }
      if (top < cur.scrollTop) {
        cur.scrollTop = top;
      }
      if (top > cur.scrollTop) {
        cur.scrollTop = top;
      }
      var offsetLeft = cur.offsetLeft, offsetTop = cur.offsetTop;
      if (cur.parentNode != cur.offsetParent) {
        offsetLeft -= cur.parentNode.offsetLeft;
        offsetTop -= cur.parentNode.offsetTop;
      }
      left += offsetLeft - cur.scrollLeft;
      top += offsetTop - cur.scrollTop;
      cur = cur.parentNode;
    }
   }-*/;

可以通过先滚动到底部然后滚动到所需的元素来实现它

scrollToTop(CellTable table, int position){
    if(table.getRowCount() > 0 && position >=0){
        //first - Scroll to bottom
        table.getRowElement(table.getRowCount() - 1).scrollIntoView();
        //second - scroll to element
        table.getRowElement(position).scrollIntoView();
    }
}