在 ASP.NET 中,鼠标悬停时高亮 GridView 行






4.94/5 (12投票s)
GridView 控件是一个可定制且灵活的控件,用于以表格形式显示数据。它具有一些不错的功能。但缺乏一些客户端
GridView 控件是一个可定制且灵活的控件,用于以表格形式显示数据。它具有一些不错的功能。但缺乏一些客户端功能,这会使 Web 用户感到满意。我们可以通过几行代码轻松添加这些功能。
例如,一个常见的任务是在鼠标悬停在 GridView 行上时高亮显示该行,而 GridView 控件本身并不提供此功能。在这里,我们将看到如何轻松完成此任务。
为了改变 GridView 行的颜色,我们需要使用 JavaScript 的 onmouseover
和 onmouseout
客户端事件,为该特定行添加/删除样式属性。我们可以在 RowDataBound
或 RowCreated
GridView 事件中执行此操作。
代码片段
protected void gvHrEmploye_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
// when mouse is over the row, save original color to new attribute, and change it to highlight color
e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#EEFFAA'");
// when mouse leaves the row, change the bg color to its original value
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
}
}
或,
protected void gvHrEmploye_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
// when mouse is over the row, save original color to new attribute, and change it to highlight color
e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#EEFFAA'");
// when mouse leaves the row, change the bg color to its original value
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle;");
}
}
即使您设置了 AlternatingRowStyle
属性,或者该行之前已被选中,它也能正常工作。