javascript - 滚动顶部不符合预期

标签 javascript jquery

注意

Reopening bounty as forgot to award it last time. Already being answered by Master A.Woff.

我想在用户展开时到达某一行(这样当最后一个可见行展开时,用户不必向下滚动即可查看内容)。

我用过

$('#example tbody').on('click', 'td .green-expand', function (event, delegated) {    

        var tr = $(this).closest('tr');
        var row = table.row(tr);


        if (row.child.isShown()) {
            if (event.originalEvent || (delegated && !$(delegated).hasClass('show'))) {
                row.child.hide();
                tr.removeClass('shown');
            }
        } else {
            if (event.originalEvent || (delegated && $(delegated).hasClass('show'))) {
                row.child(format(row.data())).show();
                tr.addClass('shown');

                var parent = $(this).closest('table');
                var scrollTo = $(this).closest('tr').position().top;

                $('.dataTables_scrollBody').animate({
                    scrollTop: scrollTo
                });
            }
        }
});

注意

展开行 - 只需单击单击超链接。它将显示行详细信息

Datatable with expand row

最佳答案

您应该使用 offsetTop 属性来获取相关的 offsetParent (参见编辑部分):

var scrollTo = tr.prop('offsetTop');

-jsFiddle-

或者将table元素位置设置为非静态:

table.dataTable { position:relative; }

-jsFiddle-

编辑:为什么 jq position().top 在这种情况下不起作用?

这是因为位置是根据 offsetParent 计算的。本质上,关于规范,offsetParent是计算位置非静态的最近祖先或body元素或td,thtable(spec) .

我怀疑,这种行为可能会返回有关浏览器实现的不同结果,无论是否遵循规范。

因此,jQuery 对其进行标准化,不是使用 native DOM 属性 offsetParent,而是使用自己的方法 $.fn.offsetParent()。该方法实现如下:

offsetParent: function () {
    return this.map(function () {
        var offsetParent = this.offsetParent || docElem;

        while (offsetParent && (!jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static")) {
            offsetParent = offsetParent.offsetParent;
        }
        return offsetParent || docElem;
    });
}

如您所见,对于任何类型的元素都没有发生元素异常(docElem 是当前文档对象)。 默认情况下,table元素位置是静态的,这就是为什么在您的示例中,jq返回为offsetParent,jQuery数据表插件使用的div包装器和不是table(遵循规范的异常(exception))。因此,原生 offsetTop 属性和 jq $.fn.position().top 返回不同的结果。

Also the currently solution does not work in all cases

(仅)在 Chrome 上测试它,我无法复制问题。

关于javascript - 滚动顶部不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938508/

相关文章:

javascript - 为什么从数据列表中选择一个项目时,值末尾的空格会消失?

javascript - 将逗号替换为空格

javascript - 在网站上推进图像 slider 时页面滚动

javascript - Twitter Bootstrap 模态 : How to remove Slide down effect

javascript - 客户端 Breeze JS

javascript - 在 Jquery 中总结和分组 JSON 对象

jquery - OCS 在基于 AJAX 的 SharePoint Web 部件中的存在

javascript - 为什么 jquery load() 方法不需要网络服务器才能正常工作?

javascript - abort() onPopstate 之后 AJAX 停止工作

javascript - 如何在表行 (tr) 上叠加一个 div(或任何元素)?