2017-03-16 52 views
2

this plunk的目标是创建一个表格,其中向上和向下键将用于以编程方式选择行并滚动浏览表格。所选行将具有不同的背景颜色。以编程方式滚动浏览表格

当键入/关闭时,我使用e.preventDefault()来避免行向上/向下移动两次。问题是,当我开始向下滚动时,行保持固定,选定的行消失。如何解决这个问题?

HTML

<div id="selector" tabindex="0" ng-keydown="scroll($event)" 
      style="width:300px;height:80px;border:1px solid gray;overflow-y:auto"> 
    <table> 
     <tr ng-repeat="item in items"> 
      <td class="td1" ng-class="{'tdactive' : $index==index }">{{item.col}}</td> 
      <td class="td1" ng-class="{'tdactive' : $index==index }">{{item.dsc}}</td> 
     </tr> 
    </table> 
</div> 

的Javascript

var app = angular.module('app', []); 

app.controller('ctl', function($scope) { 

    document.getElementById("selector").focus(); 

    $scope.items = [ {col:"aaa", dsc:"AAA1"}, {col:"bbb", dsc:"BBB2"} , {col:"ccc", dsc:"CCC3"}, 
      {col:"aaa2", dsc:"AAA21"}, {col:"bbb2", dsc:"BBB22"} , {col:"ccc2", dsc:"CCC23"}, 
      {col:"aaa2", dsc:"AAA21"}, {col:"bbb2", dsc:"BBB22"} , {col:"ccc2", dsc:"CCC23"} ]; 
    $scope.index = 0; 

    $scope.scroll = function(e) { 
     if (e.which === 40) { // down arrow 
      if ($scope.index<$scope.items.length - 1) 
       $scope.index++; 
      e.preventDefault(); 
     } 
     else if (e.which === 38) { // up arrow 
      if ($scope.index>0) 
       $scope.index--; 
      e.preventDefault(); 
     } 
    }; 
}); 

回答

3

所有你需要添加表行ID作为id="tr-{{$index}}"

然后,您可以防止您的滚动,如果TR在当前视口的第

$scope.scroll = function(e) { 
    var parentContainer = document.getElementById("selector"); 
     if (e.which === 40) { // down arrow 
      if ($scope.index<$scope.items.length - 1) 
      { 

      var element = document.getElementById("tr-"+$scope.index); 
      if(isElementInViewport(parentContainer,element)){ 
      e.preventDefault(); 
      } 

       $scope.index++; 
      } 
     } 
     else if (e.which === 38) { // up arrow 
      if ($scope.index>0) 
      { 
      var element = document.getElementById("tr-"+$scope.index); 
      if(!isElementInViewport(parentContainer,element)){ 
      e.preventDefault(); 
      } 
       $scope.index--; 
      } 
     } 
    }; 

function isElementInViewport(parent, el) { 
    if(parent==undefined || el==undefined) 
    return false; 
    var elRect = el.getBoundingClientRect(), 
     parRect = parent.getBoundingClientRect(); 
     //console.log(elRect) 
     //console.log(parRect) 
     var elementHeight = elRect.height; 
    return (
     elRect.top >= parRect.top && 
     elRect.bottom <= parRect.bottom && 
     elRect.bottom+elementHeight<= parRect.bottom 
    ); 
} 

Working Plunker

+0

我看到的问题是,当选中的行位于表底部并且按下时,那么下一行也应该位于表的底部,而不是位于中间。我试图改变桌子的高度,但它也没有工作。 – ps0604

+0

检查更新的plunker,如果这是你想要的? – amansinghgusain

+0

谢谢,它完美的作品 – ps0604