我在JavaScript中构建一个程序,该程序允许用户使用向上,向下,向左,向右按钮在表格单元格之间导航。单击方向按钮后,将突出显示相应的表格单元格。
我的表格如下:
我正在努力构建控制方向按钮的功能,但我对如何处理它非常失败。我需要能够传递包含当前突出显示的单元格的参数,但我无法弄清楚如何执行此操作。
到目前为止,我的JavaScript实际上做得不多:
function right() {
document.getElementById("one").nextElementSibling.style.border = '2px solid black';
}
如何解决这个问题的任何帮助都会很棒,因为我真的不知道如何解决这个问题。
答案 0 :(得分:3)
使用纯JS的动态解决方案
您基本上可以将表格对象存储在二维矩阵中。这样做时有两个全局坐标X和Y,用于存储当前网格位置。您可以绑定跟踪当前焦点位置的单击事件和键盘事件。
看看小提琴:https://jsfiddle.net/cnkr7wqa/5/
请注意,无论行大小或列大小,如果每行的长度相同且每列的长度相同,此解决方案都是动态的。
另请注意,这适用于:鼠标点击,方向键盘按下和按下按钮
<强> HTML 强>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<button>Left</button>
<button>Up</button>
<button>Right</button>
<button>Down</button>
<强>的Javascript 强>
var dat = document.getElementsByTagName('td');
var numOfColumns = document.getElementsByTagName('tr').length;
var numOfRows = document.getElementsByTagName('tr').length;
var currIndex = 0;
var rowObj = document.getElementsByTagName('tr');
var oneColLength = rowObj[0].children.length;
var colObj = document.getElementsByTagName('td');
var totalData = rowObj.length * colObj.length;
var dataCounter = 0;
var matrixObj = new Array(rowObj.length);
var currentX = 0;
var currentY = 0;
var buttons = document.getElementsByTagName('button');
for(var i = 0; i < matrixObj.length; i++){
matrixObj[i] = new Array(oneColLength);
}
for(var i = 0; i < numOfRows; i++){
for(var j = 0; j < oneColLength; j++){
matrixObj[i][j] = colObj[dataCounter++];
}
}
for(var i = 0; i < buttons.length; i++){
buttons[i].addEventListener("click",function(){
removeAllBorders();
compareBtnEntity(this);
});
}
for(var i = 0; i < dat.length; i++){
dat[i].addEventListener("click",function(){
removeAllBorders();
this.style.border = "1px solid red";
compareEntity(this);
});
}
window.addEventListener("keyup",function(e){
switch(e.keyCode){
case 37:
if(currentX > 0){
currentX--;
repaint();
}
break;
case 38:
if(currentY > 0){
currentY--;
repaint();
}
break;
case 39:
if(currentX < oneColLength-1){
currentX++;
repaint();
}
break;
case 40:
if(currentY < matrixObj.length-1){
currentY++;
repaint();
}
break;
}
})
function removeAllBorders(){
for(var i = 0; i < dat.length; i++){
dat[i].style.border = "1px solid grey";
}
}
function compareEntity(ele){
for(var i = 0; i < matrixObj.length; i++){
for(var j = 0; j < oneColLength; j++){
if(ele == matrixObj[i][j]){
currentX = j;
currentY = i;
}
}
}
}
function compareBtnEntity(ele){
for(var i = 0; i < buttons.length; i++){
if(buttons[i] == ele){
break;
}
}
switch(i){
case 0:
if(currentX > 0){
currentX--;
repaint();
}
break;
case 1:
if(currentY > 0){
currentY--;
repaint();
}
break;
case 2:
if(currentX < oneColLength-1){
currentX++;
repaint();
}
break;
case 3:
if(currentY < matrixObj.length-1){
currentY++;
repaint();
}
break;
}
repaint();
}
function repaint(){
removeAllBorders();
matrixObj[currentY][currentX].style.border = "1px solid red";
}
答案 1 :(得分:2)
我知道你没有在此包含<script>
function load() {
var mapWidth = 5167; //5120
var mapHeight = 4115; //4096
//var h_offset = 4115;
var url = 'maptiles/';
//var crossOrigin = 'anonymous';
var imgCenter = [mapWidth / 2, - mapHeight / 2];
//projection
var proj = new ol.proj.Projection({
code: 'ZOOMIFY',
units: 'pixels',
extent: [0, 0, mapWidth, mapHeight]
});
var source = new ol.source.Zoomify({
url: url,
size: [mapWidth, mapHeight],
//crossOrigin: crossOrigin
});
//transform the mouseposition to the map coordinates
ol.proj.addCoordinateTransforms('EPSG:4326', proj,
function(coordinate) {
return [coordinate[0], -coordinate[1]];
},
function(coordinate) {
return [coordinate[0], -coordinate[1]];
});
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.FullScreen()
]),
layers: [
new ol.layer.Tile({
source: source
})
],
target: 'map',
view: new ol.View({
projection: proj,
center: imgCenter,
zoom: 1,
maxZoom: 5
})
});
var mousePosition = new ol.control.MousePosition({
//coordinateFormat: ol.coordinate.createStringXY(),
coordinateFormat: function(coordinate) {
return ol.coordinate.format(coordinate, '{x}, {y}', 0);},
projection: 'EPSG:4326',
target: document.getElementById('mouseposition'),
undefinedHTML: ' '
});
map.addControl(mousePosition);
}
</script>
标记,但我使用jQuery创建了一个工作示例here(https://jsfiddle.net/romellem/pg6eveht/),使事情变得更容易。
没有任何过于复杂的地方,你无法删除我使用的jQuery,但我会把它作为读者的练习。 :)
我使用原型模式创建了一个hilighter类,您可以通过选择器来初始化表。它不考虑表中的标题,因此您需要添加它。
否则,希望如果你完全迷失了,这有助于你朝着正确的方向迈出一步。
jquery
$(document).ready(function() {
var TableHilighter = function(table, selected) {
this.table = $(table);
this.rows = this.table.find('tr').length;
this.cols = this.table.find('tr').first().find('td').length;
this.selected = (typeof selected === 'undefined') ? [1, 1] : selected;
// Hilight our row on initialization
this.hilight();
};
TableHilighter.prototype = {
"hilight": function(cell) {
if (typeof cell === 'undefined') {
cell = this.selected;
}
// Clear all hilighted cells
this.table.find('td').removeClass('hilighted');
// First find the row, then find the col, and add the .hilighted class
this.table.find('tr:nth-child(' + this.selected[1] + ')').find('td:nth-child(' + this.selected[0] + ')').addClass('hilighted');
},
"move": function(dir) {
switch (dir) {
case 'up':
this._up();
break;
case 'down':
this._down();
break;
case 'left':
this._left();
break;
case 'right':
this._right();
break;
default:
break;
}
this.hilight();
return this.selected;
},
"_left": function() {
if (this._x() > 1) {
this._x(this._x() - 1);
}
return this.selected;
},
"_right": function() {
if (this._x() < this.cols) {
this._x(this._x() + 1);
}
return this.selected;
},
"_up": function() {
if (this._y() > 1) {
this._y(this._y() - 1);
}
return this.selected;
},
"_down": function() {
if (this._y() < this.rows) {
this._y(this._y() + 1);
}
return this.selected;
},
"_x": function(x) {
if (typeof x === 'undefined') {
return this.selected[0];
} else {
this.selected[0] = x;
return this.selected[0];
}
},
"_y": function(y) {
if (typeof y === 'undefined') {
return this.selected[1];
} else {
this.selected[1] = y;
return this.selected[1];
}
}
};
// Initialize our TableHilighter
var my_table = new TableHilighter('table');
// Add button event handlers
$('.up').on('click', function(e) {
e.preventDefault();
my_table.move('up');
});
$('.down').on('click', function(e) {
e.preventDefault();
my_table.move('down');
});
$('.left').on('click', function(e) {
e.preventDefault();
my_table.move('left');
});
$('.right').on('click', function(e) {
e.preventDefault();
my_table.move('right');
});
});
table tr td {
border: 1px solid black;
padding: 2px;
}
.hilighted {
border: 2px solid red;
padding: 1px;
}
button.up {
margin-left: 2em;
}
button.down {
margin-left: 1.5em;
}
答案 2 :(得分:1)
解决此问题的一种便捷方法是为您的单元格提供有意义的id
。导航变得不言自明了。
var dimensionX = 4;
var dimensionY = 4;
var selected = "cell-0-0";
$(document).keydown(function(event) {
event.preventDefault();
$("#" + selected).removeClass("selected");
var currentX = parseInt(selected.split("-")[1]);
var currentY = parseInt(selected.split("-")[2]);
switch (event.which) {
case 37:
selected = "cell-" + (currentX == 0 ? dimensionX - 1 : currentX - 1) + "-" + currentY;
break;
case 38:
selected = "cell-" + currentX + "-" + (currentY == 0 ? dimensionY - 1 : currentY - 1);
break;
case 39:
selected = "cell-" + ((currentX + 1) % dimensionX) + "-" + currentY;
break;
case 40:
selected = "cell-" + currentX + "-" + ((currentY + 1) % dimensionY);
break;
}
$("#" + selected).addClass("selected");
});
$("#up, #down, #left, #right").click(function() {
var currentX = parseInt(selected.split("-")[1]);
var currentY = parseInt(selected.split("-")[2]);
$("#" + selected).removeClass("selected");
switch (this.id) {
case "up":
selected = "cell-" + currentX + "-" + (currentY == 0 ? dimensionY - 1 : currentY - 1);
break;
case "down":
selected = "cell-" + currentX + "-" + ((currentY + 1) % dimensionY);
break;
case "left":
selected = "cell-" + (currentX == 0 ? dimensionX - 1 : currentX - 1) + "-" + currentY;
break;
case "right":
selected = "cell-" + ((currentX + 1) % dimensionX) + "-" + currentY;
break;
}
$("#" + selected).addClass("selected");
});
$("#mark").click(function() {
if ($("#" + selected).hasClass("marked")) $("#" + selected).removeClass("marked");
else $("#" + selected).addClass("marked");
});
&#13;
td {
border: 1px solid black;
}
td.selected {
border: 1px solid red;
}
p.buttons > span {
border: 1px solid grey;
border-radius: 2px;
cursor: pointer;
margin: 0 3px;
display: inline-block;
padding: 1px 3px;
}
td.marked {
background: black;
color: white;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sheet">
<tbody>
<tr id="row-0">
<td id="cell-0-0" class="selected">A</td>
<td id="cell-1-0">B</td>
<td id="cell-2-0">C</td>
<td id="cell-3-0">D</td>
</tr>
<tr id="row-1">
<td id="cell-0-1">E</td>
<td id="cell-1-1">F</td>
<td id="cell-2-1">G</td>
<td id="cell-3-1">H</td>
</tr>
<tr id="row-2">
<td id="cell-0-2">I</td>
<td id="cell-1-2">J</td>
<td id="cell-2-2">K</td>
<td id="cell-3-2">L</td>
</tr>
<tr id="row-3">
<td id="cell-0-3">M</td>
<td id="cell-1-3">N</td>
<td id="cell-2-3">O</td>
<td id="cell-3-3">P</td>
</tr>
</tbody>
</table>
<p class="buttons"><span id="up">Up</span> <span id="down">Down</span> <span id="left">Left</span> <span id="right">Right</span> <span id="mark">Mark</span></p>
&#13;
您需要关注代码段以使用箭头移动。
答案 3 :(得分:0)
好吧,我为你创造了一个小提琴:
https://jsfiddle.net/c7f3hczs/
但请注意:
这仅适用于“右箭头按下”。您还需要实现其他键。向上和向下箭头有点棘手......你需要知道表格有多少列(你可以通过<tr>
找出这个数字并计算里面的所有<td>
元素它
JS:
document.addEventListener("keydown", function (e) {
if (e.keyCode == 39) document.getElementsByTagName("td").className = "";
var actualId = document.getElementsByClassName("active")[0].getAttribute("id");
var count = document.getElementsByTagName("td").length;
console.log(count)
document.getElementById(actualId).className="notActive";
if (parseInt(actualId)+1 < count) {
document.getElementById(parseInt(actualId)+1).className="active";
} else {
document.getElementById(0).className="active";
}
});
keyCode“39”是右箭头键