有没有办法用某些方法和事件来扩展标准HTML表?例如,我希望它能识别按键(向上、向下、向下、向上、向上移动、最后移动、向左移动、向右移动(。这可能吗?非常感谢
我设法用这种方式实现了它。按预期工作:
<html>
<head>
</head>
<body>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
.selected {
background-color: cyan;
color: black;
}
</style>
<table id="browse">
<tr style="background-color: blue; color:white"><th>First</th><th>Last</th></tr>
<tr class="selected"><td>Homer</td><td>Simpson</td></tr>
<tr><td>James</td><td>Webb</td></tr>
<tr><td>Robin</td><td>Hood</td></tr>
<tr><td>Bill</td><td>Gates</td></tr>
<tr><td>Steve</td><td>Jobs</td></tr>
</table>
<script>
document.onkeydown = checkKey;
function checkKey( event )
{
switch( event.keyCode )
{
case 35: // go bottom
curRow = document.querySelector( '.selected' );
if( curRow != document.getElementById( "browse" ).rows[ document.getElementById( "browse" ).rows.length - 1 ] )
{
curRow.className = "";
curRow = document.getElementById( "browse" ).rows[ document.getElementById( "browse" ).rows.length - 1 ];
curRow.className = "selected";
}
break;
case 36: // go top
curRow = document.querySelector( '.selected' );
if( curRow != document.getElementById( "browse" ).rows[ 1 ] )
{
curRow.className = "";
curRow = document.getElementById( "browse" ).rows[ 1 ];
curRow.className = "selected";
}
break;
case 38: // up
curRow = document.querySelector( '.selected' );
if( curRow != document.getElementById( "browse" ).rows[ 1 ] )
{
curRow.className = "";
curRow = curRow.previousElementSibling;
curRow.className = "selected";
}
break;
case 40: // down
curRow = document.querySelector( '.selected' );
if( curRow != document.getElementById( "browse" ).rows[ document.getElementById( "browse" ).rows.length - 1 ] )
{
curRow.className = "";
curRow = curRow.nextElementSibling;
curRow.className = "selected";
}
break;
case 33: // pageUp
curRow = document.querySelector( '.selected' );
if( curRow != document.getElementById( "browse" ).rows[ 1 ] )
{
curRow.className = "";
curRow = document.getElementById( "browse" ).rows[ 1 ];
curRow.className = "selected";
}
break;
case 34: // pageDown
curRow = document.querySelector( '.selected' );
if( curRow != document.getElementById( "browse" ).rows[ document.getElementById( "browse" ).rows.length - 1 ] )
{
curRow.className = "";
curRow = document.getElementById( "browse" ).rows[ document.getElementById( "browse" ).rows.length - 1 ];
curRow.className = "selected";
}
break;
default:
alert( event.keyCode );
}
}
</script>
</body>
</html>