당신이 원하는 꽤 많은 일을 조각입니다 :
$(document).ready(function() {
var currentRow = null, // Stores the currently hovered TR
fKey = false, // Indicates, if F has been pressed
table = $('#table'), // Holder for the table
stopBlackout = function() { // Removes "blackout"
$('body').removeClass('blackout');
if (currentRow) {
currentRow.removeClass('hilite');
}
},
// Starts "blackout"
startBlackout = function (row) { // row = row element
row.addClass('hilite');
$('body').addClass('blackout');
if (currentRow[0] !== row[0]) { // Remove hilite if different row only
currentRow.removeClass('hilite');
}
currentRow = row;
},
// Keydown listener toggles "blackout"
toggleBlackout = function (e) { // e = event object
if ('form' in e.target) {return;} // Exit if a form element is active
if (e.which === 27 || e.which === 70) { // Action when hit Esc or F only
fKey = !fKey;
if (e.which === 27) {
fKey = false;
}
if (!fKey) {
stopBlackout();
} else if (currentRow) { // Start "blackout" when having a hovered row
startBlackout(currentRow);
}
}
};
table.mouseenter(function() { // Activate table to receive key presses
this.focus();
});
table.mouseleave(function() { // End "blackout" and stop receiving keypresses
stopBlackout();
table.blur();
});
table.keydown(toggleBlackout);
table.mouseover(function (e) { // Highlight active row according to mouse hover
var row = $(e.target);
if (row[0].tagName !== 'TR') { // Usually TD or other element triggers mouseover
row = row.closest('tr'); // Set target to TR
if (!row.length) {return;} // Exit if e.target was TBODY or TABLE
if (fKey) {
startBlackout(row);
}
currentRow = row; // Update the currently hovered row holder
}
});
});
.blackout {
background: #000000;
}
.hilite {
background: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table" tabindex="-1">
<tr><td>R1<b>C</b>1</td><td>R1C2</td></tr>
<tr><td>R1C2</td><td>R2C2</td></tr>
<tr><td>R1C3</td><td>R3C2</td></tr>
<tr><td>R1C4</td><td>R4C2</td></tr>
</table>
일부 설명
모든 이벤트가 자식 요소가 아닌 테이블 요소에 연결되어 있습니다. 이렇게하면 페이지의 이벤트 리스너가 줄어들어 특히 테이블이 매우 큰 경우 더욱 빠르게 수행 할 수 있습니다.이러한 수신기를 추가하기 전에 표가 있어야하지만 나중에 콘텐츠를 추가 할 수 있습니다. Esc를 모든 브라우저에서 keypress
을 발생하지 않기 때문에
keydown
가 사용됩니다.
fKey
코드의 변수는 "정전"이 켜져 있는지 여부를 나타냅니다.
활성화 키 (F)는 테이블 위에 마우스를 올려 놓을 때만 작동하지만 양식 요소가 활성화되어있는 경우에는 작동하지 않습니다.
mouseover
은 tr
내에있는 요소에서 다른 요소로 마우스를 이동할 때마다 발생하므로 처리기에 몇 가지 추가 검사가 있습니다.
mouseenter
처리기가 테이블 위에 마우스를 올리면 자동으로 키 누름을받으며 테이블을 먼저 활성화 할 필요가 없습니다.
mouseleave
처리기가 키 누름을받는 테이블을 중지하고 "정전"을 제거합니다.
tabindex
은 -1
으로 설정되어 테이블에 포커스를받을 수 있지만 탭 순서를 벗어날 수 있습니다.
이것은 실제로 매우 광범위한 질문입니다. 현재의 시도를 너무 광범위하게 생각한다고 말하고 싶습니다. 'f' 대신 CTRL (SHIFT 나 ALT도 가능)을 받아 들일 수 있다면, 그 작업은 훨씬 간단해질 것입니다. 또한 테이블이 얼마나 큰지를 아는 것이 중요합니다. 수백 줄? 수천? 자식 요소가'td' 안에 있거나 내용이 항상 일반 텍스트입니까? 'td' 스타일은 어떤가요? 어때요? "블랙 아웃"은'body'의 배경을 충분히 검은 색으로 설정하거나 커버 요소를 사용하려고 생각한 적이 있습니까? – Teemu
블랙 아웃 부분에 대한 아이디어가 있다면 제안을 위해 열어 둡니다. – Damien