【发布时间】:2017-01-23 20:47:27
【问题描述】:
我正在尝试使用 animate 函数滚动到表格的特定行。当可滚动的 div 位于其顶部时它工作正常,但是当我从顶部滚动时,它只会得到它看起来可见的顶部。
我在一个对话框(引导模式窗口)中使用它。有没有办法获得与 div 顶部的距离而不仅仅是可见的距离?
下面的 HTML 代码是进入引导模式窗口(对话框)的 asp.net mvc4 部分类的一部分:
<div id="LocationNumberModalAllLocations" style="Margin-top: -9px">
<div class="container">
<div class="row row-eq-height">
<div class="col-sm-12 col-md-4">
<div id="LocationNumberModalAllLocationsSelectionContainer" class="ModalResultsTable">
<table id="locationList" class="table table-hover table-condensed">
<thead>
<tr>
<th>Location</th>
<th>Items</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="col-sm-12 col-md-8 modalTableColumnCanvas">
<center><div id="control" style="Margin:-11px 0 5px 0">
Go to location: <input type="text" size="10" id="GoToLocationInput" /> <button onclick='gotoLocation()'> Go </button>
</div></center>
<div class="modalTableCanvas">
<div class="ModalSelectedTable">
<center><h4>Selected Location's Inventory</h4></center>
</div>
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Part Number</th>
<th>Condition</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
这是我的 jquery 代码。
function gotoLocation() {
//check if value exists
var tableOfLocations = $('#locationList');
var location = $('#GoToLocationInput').val();
var tableRow = $('#locationList tbody tr td').filter(function () {
return $(this).text() == location;
});
if (tableRow.length) {
var container = $('#LocationNumberModalAllLocationsSelectionContainer');
var height = container.height();
var tableRowPosition = tableRow.offset().top;
container.animate({ scrollTop: tableRowPosition - (height / 2) }, 1000);
}
}
示例: jsfiddle.net/eaglei22/vgutew90
【问题讨论】:
-
能否也发布您的 HTML 代码?
-
@ObsidianAge 好的,我发布了与该功能一起使用的 html。
-
完全按照原样复制代码给我
gotoLocation is not defined。您是否遇到同样的错误? -
不,我不明白,让我看看我是否可以拼凑一个 JSFiddle。顺便说一句,我确实找到了某种解决方案,首先将 div 放在顶部,就像这样,container.scrollTop(0).. 在定义 tableRowPosition 之前调用它。缺点是即使它已经在该位置,也会从顶部滚动回该位置。这不是一个糟糕的解决方案,我可能只是添加一些检查以查看输入是否与当前表值匹配。但我仍然想知道为什么反应会是这样。
-
@ObsidianAge jsfiddle.net/eaglei22/vgutew90 这是我的例子。如果您尝试转到 99,然后转到 50,您会看到它在尝试转到 50 时只是滚动回顶部。那是因为第二次尝试时 offset.top 值非常小,这让我相信它只是从屏幕上显示的 div 顶部抓取它。我的解决方案确实解决了它,但似乎不是最好的解决方案。有任何想法吗?谢谢!
标签: javascript jquery html twitter-bootstrap asp.net-mvc-4