javascript - 获取表格中行的背景以通过单击更改?

标签 javascript css gwt

当用户执行正确的点击时,如何让表格中的行的背景改变颜色?

我通过 :active 伪类尝试了这个,但没有按我想要的那样工作。例如,在移动设备触摸屏上,只要用户触摸屏幕,相交的行就会改变颜色,即使这不是点击 [点击是 mouseDown+mouseUp 的短组合]。

这是表格:

<table>
  <tbody>
    <tr>
      <td align="left" style="vertical-align: top;">
        <div class="GPBYFDEEB" 
          __gwtcellbasedwidgetimpldispatchingfocus="true" 
          __gwtcellbasedwidgetimpldispatchingblur="true">
          <div>
            <div class="GPBYFDEAB" tabindex="0" style="outline:none;" __idx="0" onclick="">
              <div class="GPBYFDECB" style="outline:none;" __idx="1" onclick="">
                <!-- finally this is me. -->
                <div class="tableRow"> 

这是我的CSS:

.tableRow {
    background-color: green;
}

.tableRow:active {
    background-color: red;
}

有没有办法做到这一点? (我正在使用 gwt 来生成上面的 html,但这里并不重要)。

准确地说,我希望在点击事件发生后,行的背景色变为红色。片刻之后,将背景恢复为原始颜色。我基本上是在尝试重现在 iOS 或 android native 小部件上单击列表项的视觉效果。 谢谢

最佳答案

JavaScript 让它变得非常简单:

var rows = document.getElementsByClassName("tableRow"); //get the rows
var n = rows.length; //get no. of rows
for(var i = 0; i < n; i ++) {
    var cur = rows[i]; //get the current row;
    cur.onmousedown = function() { //when this row is clicked
        this.style.backgroundColor = "red"; //make its background red
    };
    cur.onmouseup = function() {
        this.style.backgroundColor = "green";
    }
}

如果你有 jQuery,那就更简单了:

$(".tableRow").mousedown(function() {
     $(this).css("background-color", "red");
});

$(".tableRow").mouseup(function() {
     $(this).css("background-color", "green");
});

一个使用纯 JavaScript 版本的小演示:little link . (我冒昧地稍微改变了颜色!)。

关于javascript - 获取表格中行的背景以通过单击更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12332714/

相关文章:

gwt - 为什么我不能添加从 SimplePanel 扩展到 RootPanel 的类?

php - 使用 Jquery/javascript 添加大量 HTML

html - 如何将输入定位在它自己的 div 的左下角

javascript - 将对象插入对象数组 - Typescript

html - ionic : put a div vertically centre in the page which contains 3 Buttons

html - 居中一个没有设置宽度的div容器

java - Applet 以外的选项

java - 如何分配唯一的 DOM 元素 ID

javascript - 尝试将 HTML 文件转换为包含套接字 io 的 JavaScript 时出现语法错误,SyntaxError : Unexpected token <

Javascript 日期范围选择器 - 用于范围选择的单一日历