我有一个表,当用户点击表中的行时,我正在使用该行的selected属性。在其他面板中,我有一张地图,上面显示了所有员工。表中的每一行都有唯一的ID,当用户点击地图上的员工图像时,表中的员工行会突出显示。现在如果表有40行,我会显示垂直滚动条。当我点击具有Id 40的员工时,表中的行被选中但该行未显示在视图中,因为该表具有滚动条并且被滚动条隐藏。以下是我的HTML代码:
<div class="customTable">
<table class="table" id="employeesTable">
<thead class="active">
<tr>
<th>employee ID</th>
<th>employee State</th>
</tr>
</thead>
<tbody>
<div>
<tr ng-repeat="employee in employees ng-class="{'selected':employee.empId == selectedRow}" id="row{{employee.empId}}" " style="cursor: pointer">
<td>{{employee.empId}}</a></td>
<td><span>{{employee.employeeState}}</span></td>
</tr>
</div>
</tbody>
</table>
</div>
现在当我点击地图上的员工图片时,会调用以下代码:
$scope.employeeDisplay = function(employee){
//to display employee in the table
//called when the employee is clicked on the map
var id = employee.empId;
$('#employeesTable tr').eq(1).removeClass('selected');
$scope.selectedRow = empId //so based on the employee is that particular row is highlighted in the table
}
如果行不在初始视图中,您是否可以让我知道表如何自动显示所选行,如表中仅显示20行,如果选择了ID为40的员工,则表应滚动到所选行。
答案 0 :(得分:0)
这是一个JSFiddle,它具有您正在寻找的基本行为。它只是滚动到第40个元素,如果它还没有在视图中。
https://jsfiddle.net/reid_horton/odd0omk7/1/
它的工作原理是将滚动条元素的scrollTop
属性设置为要查看的项目的offsetTop
属性,从而将滚动条滚动到元素位于顶部的位置。视口。
要检查项目是否已在视图中,它会将滚动条的当前位置与元素的位置进行比较。然后,它使用视口的高度来确定元素是否在可查看的值范围内。
HTML
<div ng-app="myApp" ng-controller="MainCtrl">
<div class="scrolling-container">
<table>
<tr ng-repeat="k in items">
<td>{{ k }}</td>
</tr>
</table>
</div>
<!-- As an example, scroll to the 40th element -->
<button ng-click="scrollItemIntoView()">
Scroll to Bottom
</button>
</div>
JS
var app = angular.module("myApp", []);
app.controller("MainCtrl", function($scope) {
// Populate the table with 0..100
$scope.items = [];
for (var i = 0; i < 100; i++) {
$scope.items.push(i);
}
// This function is called when the button is clicked.
$scope.scrollItemIntoView = function() {
var scrollElement = $('.scrolling-container')[0];
var itemToView = $('tr')[40];
// This is where it all goes down.
if (!itemIsInViewport(itemToView)) {
scrollElement.scrollTop = itemToView.offsetTop;
}
// Determines if the item is already in view.
function itemIsInViewport(item) {
var $scrollElement = $('.scrolling-container');
var upperBound = item.offsetTop;
var lowerBound = item.offsetTop - $scrollElement.innerHeight();
var currentPosition = $scrollElement.scrollTop();
return lowerBound < currentPosition && currentPosition < upperBound;
}
}
});