CSS expression 实现表格隔行换色与表头高亮
CSS expression 是旧版 Internet Explorer 特有的一种功能,允许在样式表中直接书写脚本以动态计算属性值。在没有 JavaScript 或现代 CSS 选择器的条件下,开发人员常利用此特性在表格(<table>)中实现隔行换色及首行高亮。
基础隔行换色与首行独立设置
expression 的核心在于通过 DOM 对象判断当前元素的状态并返回对应的值。要实现表格第一行颜色不同,其余行奇偶交替的效果,可以通过 this.sectionRowIndex(获取当前行的索引)配合三元运算符完成。
操作逻辑如下:
- 检查
sectionRowIndex == 0:如果是首行,返回指定颜色(如灰色)。 - 检查
sectionRowIndex % 2 == 0:如果是偶数行(第0,2,4...行),返回一种颜色(如浅色粉)。 - 否则:返回第三种颜色(如浅蓝)。
完整实现代码如下:
<html>
<head>
<style type="text/css">
<!--
tr {
background-color: expression(this.sectionRowIndex==0?"#AFAFAF":((this.sectionRowIndex%2==0) ? "#FFF0F0" : "#F0F0FF"));
}
--></style>
</head>
<body>
<table cellspacing="1">
<tr><td>测试数据</td><td>测试数据</td></tr>
<tr><td>测试数据</td><td>测试数据</td></tr>
<tr><td>测试数据</td><td>测试数据</td></tr>
</table>
</body>
</html>
高级效果:包含鼠标悬停互动与首列区分
在实际业务需求中,往往还要求鼠标悬停在某一行时,该行整体变色;或者表格的第一列具有特殊的背景底色。expression 的强大之处在于它可以同时挂载事件监听器(如 onmouseover 和 onmouseout)并在定义样式的同时触发逻辑。
第1步:定义表格容器 ID
首先为表格设置一个唯一的 ID(如 DataGrid1),以便后续通过 #DataGrid1 tr 进行精确的样式控制,避免影响页面其他表格。
第2步:编写带有交互功能的 expression 表达式
在 <style> 标签中,针对 tr 和 td 编写复杂的逻辑。其中包含了对 color、font-weight 以及自定义 CSS 属性 TableSelect 的控制。
关键参数说明:
onmouseover:当鼠标进入行时执行函数,将该行背景改为蓝色 (#69cdff)。onmouseout:当鼠标离开行时执行函数,恢复该行原本基于索引的颜色。expression(...):括号内的逻辑会优先执行,从而在样式加载时即绑定事件。
<style type="text/css">
#DataGrid1 tr {
/* 背景色:首行红色,偶数行浅色粉,奇数行浅蓝 */
background-color: expression(
this.sectionRowIndex == 0 ? "#FFCCCC" :
(this.sectionRowIndex % 2 == 0) ? "#FFF0F0" : "#F0F0FF"
);
/* 文字样式:首行白字加粗,其余正常 */
color: expression(this.sectionRowIndex == 0 ? "#FFFFFF" : "");
font-weight: expression(this.sectionRowIndex == 0 ? "BOLD" : "");
/* TableSelect 自定义逻辑:处理鼠标移入移出事件 */
TableSelect: expression(
this.sectionRowIndex == 0 ? "" :
(
onmouseover = function()
{
this.style.backgroundColor =
(this.style.backgroundColor != "#69cdff" ?
"#69cdff" :
(this.sectionRowIndex == 0 ? "#FFCCCC" :
(this.sectionRowIndex % 2 == 0 ? "#FFF0F0" : "#F0F0FF")
)
)
},
onmouseout = function()
{
this.style.backgroundColor =
(this.style.backgroundColor != "#69cdff" ?
"#69cdff" :
(this.sectionRowIndex == 0 ? "#FFCCCC" :
(this.sectionRowIndex % 2 == 0 ? "#FFF0F0" : "#F0F0FF")
)
)
}
)
);
}
/* 首列单独设置背景 */
#DataGrid1 td {
background-color: expression(
this.cellIndex == 0 ?
(this.parentElement.sectionRowIndex == 0 ? "#FFCCCC" : "#DDDDDD")
: null
);
}
</style>
应用该样式的 HTML 结构应包含 ID="DataGrid1" 属性:
<table cellspacing="1" id="DataGrid1">
<tr><td>标题</td><td>数值1</td></tr>
<tr><td>标题</td><td>数值2</td></tr>
</table>
注意事项与维护建议
虽然 expression 提供了强大的动态样式能力,但在现代 Web 开发中已不推荐使用。主要因为以下原因:
- 性能问题:
expression中的脚本会在页面滚动、缩放以及鼠标移动等任何导致重绘的事件中被反复调用,极易导致页面卡顿。 - 兼容性缺失:仅支持 Internet Explorer 6、7 和 8。Chrome、Firefox 及新版 Edge 均不支持此语法,且在 IE9+ 模式中已被移除。
- 可维护性差:将复杂的业务逻辑写在 CSS 文件中不利于后期调试和维护。
建议在非必须兼容老旧 IE 浏览器的场景下,改用 JavaScript 遍历添加类名(如 .odd, .even),或使用 CSS 伪类 :nth-child() 来实现相同效果。
以上就是使用 CSS expression 实现表格隔行换色与复杂交互效果的详细内容,更多关于 CSS 技巧的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









