问题描述
我想在用户展开时到达某一行(以便最后一次)可见行被扩展,用户无需向下滚动即可查看内容。
I want to reach to a certain row when a user expands it (so that when last visible row gets expanded, the user doesn't have to scroll down to see the content).
我用过,
$('#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
});
}
}
});
注意
展开行 - 只需点击点击
超链接。它将显示行详细信息
Expand row - just click on click
hyperlink. It will show row details
推荐答案
您应该使用 offsetTop
属性得到相关 offsetParent
(参见编辑部分):
You should use offsetTop
property instead to get relevant offsetParent
(see edit part):
var scrollTo = tr.prop('offsetTop');
或设置表
元素位置不是静态的:
Or set table
element position not static:
table.dataTable {position:relative; }
编辑: 为什么jq position()。top
在这种情况下不起作用?
Why jq position().top
doesn't work in this case?
这是因为计算的位置是关于 offsetParent
。本地,关于规范,offsetParent是最近的祖先,计算位置不是静态或 body
元素或 td,th
或表
()。
This is because position is calculated regarding offsetParent
. Natively, regarding spec, the offsetParent is the nearest ancestor with computed position not static or the body
element or td, th
or table
(spec).
我怀疑这种行为可以返回与浏览器实现不同的结果,遵循规范与否。
This behaviour, i suspect, can return different result regarding browser implementation, following the spec or not.
因此,jQuery对其进行规范化,不使用本机DOM属性 offsetParent
但是自己的方法 $ .fn.offsetParent()
。此方法实现如下:
So, jQuery normalizes it, not using native DOM property offsetParent
but own method $.fn.offsetParent()
. This method implementation is as follow:
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 datatable插件使用的 div
包装器,而不是表
(规范之后的例外)。因此,原生 offsetTop
属性和jq $。fn.position()。top
会返回不同的结果。
As you can see, no element exception is done regarding any type of element (docElem
is the current document object).By default, table
element position is static, that's why in your example, jq returns as offsetParent
, the div
wrapper used by jQuery datatable plugin and not the table
(exception following spec). And so, native offsetTop
property and jq $.fn.position().top
returns different result.
在chrome(仅)上测试它,我无法复制问题。
Testing it on chrome (only), i cannot replicate issue.
这篇关于scrollTop并不像预期的那样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!