How to change background color of table row (tr) when input is ":focus"?
My HTML:
<tr><td>Text</td><td><input type="text" value=""></td></tr>
My CSS:
input:focus tr{ background-color:#fff;}
I want to highlight the row in white when I'm writing text in the input field. I know "tr" is before "input", but is this possi开发者_Go百科ble to do in any way?
Thanks a bunch
No, sadly. See: Complex CSS selector for parent of active child
Here's how you could do it, though: http://jsfiddle.net/minitech/udzcp/
Using JQuery, it is very possible. Observe:
HTML
<table border="1" cellpadding="20">
<tr>
<td>Text</td>
<td height="50" width="100" id="somename"><input type="text" value="" id="mirza"></td>
</tr>
<tr><td> </td><td> </td></tr>
<tr><td>a </td><td>1 </td></tr>
<tr><td>a </td><td>1 </td></tr>
<tr><td>a </td><td>1 </td></tr>
<tr><td>a </td><td>1 </td></tr>
<tr><td>a </td><td>1 </td></tr>
</table>
CSS
.highlightedRow { background-color: orange; }
Jquery
$('input').focus(function() {
$(this).parent().parent().addClass('highlightedRow');
});
$('input').blur(function() {
$(this).parent().parent().removeClass('highlightedRow');
});
Sadly, there's no way to style the parent element with CSS, so you'll have to use javascript.
This is good for when you are generating a lot of similar rows (looping through large datasets, etc): Script:
function rowSet(data_id){
document.getElementById('row_' + data_id).style.backgroundColor = 'blue';
}
function rowReset(data_id){
document.getElementById('row_' + data_id).style.backgroundColor = '';
}
Body:
<body>
<form>
<table>
<tr id="row_#data_id#">
<td><input name="input1_#data_id#" onFocus="rowSet(#data_id#);" onBlur="rowReset(#data_id#);"></td>
<td><input name="input2_#data_id#" onFocus="rowSet(#data_id#);" onBlur="rowReset(#data_id#);"></td>
</tr>
</table>
</form>
</body>
You could also use currentRow, or whatever you prefer.
This jquery code should do it:
$('input').focus(function() {
$('tr').css("background-color", "#c00");
});
Demo here
精彩评论