所以,我有一个数独生成器,当通过 API 访问时,它会生成一个数独板(JSON 数组),然后使用 AngularJS 和 ng-repeat 在表格中我在页面上显示数独板。
到目前为止,这就是我所拥有的。我想要实现的是突出显示框中的所有元素以及行和列。现在行和列已突出显示,但我如何突出显示下图中标有黄色的元素,因为这些元素属于该框:
这是我的 HTML 代码:
<body ng-app="Sudoku">
<!-- SUDOKU BOARD -->
<div class="sudoku-game" ng-controller="SudokuController">
<table class="sudoku-board" ng-init="getSudoku()">
<tbody>
<tr ng-repeat="sudoku in sudokuGrid track by $index" ng-init="row = $index" class="sudoku-row" ng-class="{'highlight':rowSelected === row}">
<td ng-repeat="number in sudoku track by $index" ng-init="col = $index" class="sudoku-col" ng-class="{'highlight':colSelected === col}">
<div class="sudoku-cell" ng-class="{'selected':isSelected === ((row*10) + col)}" ng-click="selectedCell(row, col)" ng-keyup="insertNum($event)" tabindex="1">
<span class="prevalued" ng-if="number !== null" ng-bind="number"></span>
<span class="emptycell" ng-if="number === null" ng-bind="emptyCell"></span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
这是我的 JavaScript 代码,用于 selectedCell(row, col) 函数
$scope.getCellPosition = function (row, col) {
return (row * 10) + col;
}
$scope.selectedCell = function (row, col) {
$scope.isSelected = $scope.getCellPosition(row, col);
$scope.rowSelected = row;
$scope.colSelected = col;
console.log($scope.isSelected);
}
这是我从 API 获取 JSON 格式的数独板数据的方法:
[
[
9,
2,
null,
null,
null,
null,
null,
3,
8
],
[
5,
4,
3,
9,
null,
null,
7,
null,
null
],
[
null,
null,
null,
3,
null,
null,
null,
null,
null
],
[
1,
7,
null,
null,
3,
9,
4,
5,
null
],
[
8,
3,
5,
null,
1,
null,
null,
9,
null
],
[
null,
9,
2,
5,
7,
6,
null,
1,
3
],
[
null,
1,
8,
null,
null,
5,
null,
2,
null
],
[
null,
null,
null,
6,
null,
null,
null,
7,
null
],
[
null,
null,
4,
2,
null,
null,
null,
8,
null
]
]
最佳答案
您可以向所选单元格的正方形中的单元格添加突出显示类:
<div class="sudoku-cell" ng-class="{
'selected':isSelected === ((row*10) + col),
'highlight': isHighlight(row, col),
}" ng-click="selectedCell(row, col)" ng-keyup="insertNum($event)" tabindex="1">
在你的js中:
$scope.isHighlight = function (row, col) {
// Add debugging functions
//
console.log({
row,
rowSelected: $scope.rowSelected,
col,
colSelected: $scope.colSelected,
});
// Return the boolean
//
return Math.floor(row / 3) === Math.floor($scope.rowSelected / 3)
&& Math.floor(col / 3) === Math.floor($scope.colSelected / 3)
}
关于javascript - AngularJS 中的数独,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60961153/