1:为什么要写这个方法
在项目中,一些table都要设置样式,为了样式的美观,表头是一个样式,奇数行一个样式,偶数行一个样式。当鼠标经过的时候颜色变化,鼠标离开时颜色恢复,这就有了这样方法。
2:实现过程
js文件xs_table_css.js
复制代码 代码如下:
$(document).ready(function () {
var xs_table_css = xs_table; //获取table的css
var xs_table_th_css = xs_table_th; //table 的th样式
var xs_table_even_css = xs_table_even; //table的偶数行css
var xs_table_odd_css = xs_table_odd; //table的奇数行css
var xs_table_select_css = xs_table_select; //table选择行的样式
var xs_table = table. + xs_table_css;
$(xs_table).each(function () {
$(this).children().children().has(th).addclass(xs_table_th_css); //表头
var tr_even = $(this).children().children(:even).has(td); //数据偶数行
var tr_odd = $(this).children().children(:odd).has(td); //数据奇数行
tr_even.addclass(xs_table_even_css);
tr_odd.addclass(xs_table_odd_css);
tr_even.mouseover(function () {
$(this).removeclass(xs_table_even_css);
$(this).addclass(xs_table_select_css);
});
tr_even.mouseout(function () {
$(this).removeclass(xs_table_select_css);
$(this).addclass(xs_table_even_css);
});
tr_odd.mouseover(function () {
$(this).removeclass(xs_table_odd_css);
$(this).addclass(xs_table_select_css);
});
tr_odd.mouseout(function () {
$(this).removeclass(xs_table_select_css);
$(this).addclass(xs_table_odd_css);
});
});
});
样式文件xs_table.css
复制代码 代码如下:
.xs_table
{
}
.xs_table_th
{
height: 50px;
background-color: #c0c0c0;
}
.xs_table_even
{
height: 50px;
background-color: #f0f0f0;
}.xs_table_odd
{
height: 50px;
background-color: #ffffff;
}
.xs_table_select
{
height: 50px;
background-color: #d9d9d9;
}
页面文件xs_table_css.htm
复制代码 代码如下:
ttp://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd>
http://www.w3.org/1999/xhtml>
headoneheadtwo
第一行 111111111
第二行 222222222
第三行 333333333
第四行 444444444
headoneheadtwo
第一行 111111111
第二行 222222222
第三行 333333333
第四行 444444444
3:方法说明
(1)mouseover和mouseout要先移除上次的css,不然会出现样式叠加
(2)找tr时注意tbody,虽然页面上没有tbody标签,但是默认会有这个子元素
(3)奇偶行要去除th,只找td的