Kendo Grid滚动到选定的行

gar*_*lur 9 asp.net-mvc jquery asp.net-mvc-4 kendo-ui kendo-grid

我希望能够调用一个将Kendo网格滚动到所选行的函数.我已经尝试了一些方法,但没有一个方法有效,

比如我试过这个:

var grid = $("#Grid").data("kendoGrid"),
    content = $(".k-grid-content");
content.scrollTop(grid.select());
Run Code Online (Sandbox Code Playgroud)

我也试过这个:

var gr = $("#Grid").data("kendoGrid");
var dataItem = gr.dataSource.view()[gr.select().closest("tr").index()];
var material = dataItem.id;
var row = grid.tbody.find(">tr:not(.k-grouping-row)").filter(function (i) {
    return (this.dataset.id == material);
});
content.scrollTop(row);
Run Code Online (Sandbox Code Playgroud)

有人能指出我正确的方向吗?:)

---编辑---

由于其他原因,我无法绑定到更改事件,因此我必须能够调用函数将列表滚动到所选行.这就是我试着用@Antonis为我提供的答案.

var grid = $("#Grid").data("kendoGrid")
grid.element.find(".k-grid-content").animate({  
    scrollTop: this.select().offset().top  
 }, 400);
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时,它在列表中向下滚动但不向所选行滚动.我通过调用scrollTop以错误的方式使用网格对象吗?

这个也是:

var grid = $("#ItemGrid").data("kendoGrid");
grid.scrollToSelectedRow = function () {
    var selectedRow = this.select();
    if (!selectedRow) {    
        return false;    
    }
    this.element.find(".k-grid-content").animate({
        scrollTop: selectedRow.offset().top  
    }, 400);
    return true;
    };

grid.scrollToSelectedRow();
Run Code Online (Sandbox Code Playgroud)

KRy*_*yan 14

因此,这里的大部分答案都是犯了两个错误,一个只是效率问题,另一个是实际错误.

  1. element.find(".k-grid-content").这只是大量不必要的.grid.content更容易(更快)给你完全相同的东西.

  2. 使用.offset()找到行的位置.这是不正确的:它将告诉您行相对于文档本身的位置.如果您的页面允许您滚动整个页面(而不仅仅是网格),则此数字将不正确.

    而是使用.position() - 这将为您提供相对于偏移父项的位置.为了.position()给你正确的数字,你grid.content必须拥有的表格position: relative.这最适用于CSS样式表:

    .k-grid-content table {
      position: relative;
    }

无论如何,假设您已经有一个引用(我将调用它grid)到网格本身,并且您将内容窗格设置为relative位置,您所要做的就是:

grid.content.scrollTop(grid.select().position().top);
Run Code Online (Sandbox Code Playgroud)

或者,对于动画,

grid.content.animate({ scrollTop: grid.select().position().top }, 400);
Run Code Online (Sandbox Code Playgroud)

如前所述,grid.content获取内容窗格,即要实际滚动的部分.它是一个jQuery对象.

jQuery对象有一个.scrollTop方法,因此该部分非常简单..animate使用其scrollTop属性时,该方法的工作方式类似.现在我们只需要知道滚动哪里.

为此,grid.select()返回与所选行对应的jQuery对象.这就是你要滚动到的地方.为了获得它的位置,我们使用jQuery .position()方法.返回值是一个带有topleft字段的对象; 我们想滚动到它的垂直位置,所以我们使用top.

当然,这在change回调中最容易使用; 有grid根本this(因为调用回调函数对电网本身),并change自动调用选择更改时.但是,只要您想要滚动到选择,就可以调用此代码; 你可以grid通过使用:

grid = $('#theGridsId').data('kendoGrid');
Run Code Online (Sandbox Code Playgroud)


Ant*_*anK 6

选择行时,您可以自动执行此操作.将函数绑定到"更改"事件,然后在那里,您可以滚动到所选行.(假设您只能选择一行,由'this.select()'给出)

JSFiddle示例

'变更'处理程序

//    bind to 'change' event
function onChangeSelection(e) {

    //    animate our scroll
    this.element.find(".k-grid-content").animate({  // use $('html, body') if you want to scroll the body and not the k-grid-content div
        scrollTop: this.select().offset().top  //  scroll to the selected row given by 'this.select()'
     }, 400);
}
Run Code Online (Sandbox Code Playgroud)