我想在用户选择里面的文本框时更改tr元素的颜色.焦点伪类没有使用它.没有JavaScript可以实现吗?
HTML:
<table>
<tr>
<td>Name</td><td><input type="text" name="name"></td>
</tr>
</table>?
Run Code Online (Sandbox Code Playgroud)
CSS:
tr:focus
{
background:yellow;
}?
Run Code Online (Sandbox Code Playgroud)
Update1:
看起来没有CSS only方法.使用JavaScript最简单的方法是什么?
小智 8
如何使用 :focus-within...
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
</table>?
Run Code Online (Sandbox Code Playgroud)
CSS:
tr:focus-within {
background:yellow;
}?
Run Code Online (Sandbox Code Playgroud)
什么帮助了我。因为选择的答案对我不起作用。
不.在CSS3中没有主题选择器,但CSS4中会有一个.
编辑:
纯JavaScript解决方案可以
var i;
var inputs = document.querySelectorAll("tr > td > input");
for(i = 0; i < inputs.length; ++i){
inputs[i].addEventListener('focus',function(e){
this.parentNode.parentNode.className += ' highlight';
});
inputs[i].addEventListener('blur',function(e){
this.parentNode.parentNode.className = this.parentNode.parentNode.className.replace(/\s*highlight\s*/ig,' ');
});
}
Run Code Online (Sandbox Code Playgroud)
但是,这在IE≤7中不起作用,因为之前的8节之前不知道document.querySelectorAll(演示).如果您想要一个免费的跨浏览器解决方案,您可以使用jQuery和以下代码(演示):
$("tr > td > input").focus(function(e){
$(this).parent().parent().addClass('highlight');
}).blur(function(e){
$(this).parent().parent().removeClass('highlight');
});
Run Code Online (Sandbox Code Playgroud)
不要忘记tr.highlight在CSS中添加一个类.请记住,jQuery将在以后的版本中放弃对旧浏览器的支持(请参阅浏览器支持),因此您必须使用jQuery 1.x forIE≤8.