更改< tr>的颜色当里面的元素是焦点 [英] Change color of <tr> when element inside is in focus

查看:254
本文介绍了更改< tr>的颜色当里面的元素是焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户选择一个文本框时,我想改变tr元素的颜色。焦点伪类不适用于它。

code><表>
< tr>
< td>名称< / td>< td>< input type =textname =name>< / td>
< / tr>
< / table>

CSS:

  tr:focus 
{
background:yellow;

Update1:​​

看起来像没有CSS唯一的方法。使用JavaScript来做这件事最简单的方法是什么?

解决方案

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,'');
});
}

然而,这在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');
});

不要忘记添加一个类 tr.highlight 到你的CSS。请记住,jQuery将在未来版本中放弃对旧浏览器的支持(请参阅浏览器支持),所以您必须使用jQuery 1.x for IE&8;


I want to change the color of tr element when user select a text box inside it. The focus pseudo-class is not working with it. Can this be achieved without JavaScript ?

html:

<table>
<tr>
    <td>Name</td><td><input type="text" name="name"></td>
</tr>
</table>​

CSS:

tr:focus
{
    background:yellow;
}​

Update1:
Looks like there is no CSS only method. What is the easiest way to do this using JavaScript ?

解决方案

No. There's no subject selector in CSS3, there will be one in CSS4 though.

EDIT:

A pure JavaScript solution could be

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,' ');
    });
}

However, this won't work in IE≤7, as versons prior 8 don't know document.querySelectorAll (demonstration). If you want a care-free cross-browser solution you could use jQuery and the following code (demonstration):

$("tr > td > input").focus(function(e){
    $(this).parent().parent().addClass('highlight');
}).blur(function(e){
    $(this).parent().parent().removeClass('highlight');
});

Don't forget to add a class tr.highlight to your CSS. Keep in mind that jQuery will drop support of old browsers in future releases (see Browser Support), so you'll have to use jQuery 1.x for IE ≤8.

这篇关于更改&lt; tr&gt;的颜色当里面的元素是焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆