.Net Gridview在鼠标悬停后恢复交替颜色

时间:2011-01-04 19:38:40

标签: c# gridview

我有一个gridview,其中包含alternatingRowStyle属性。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource2" OnRowDataBound="GridView1_RowDataBound"
        onselectedindexchanged="GridView1_SelectedIndexChanged" AlternatingRowStyle-BackColor="#f0f1f3">

我还希望在光标移动时突出显示行:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
{  
        if (e.Row.RowType == DataControlRowType.DataRow)  
        {  
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ceedfc'");  
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=''");  
            e.Row.Attributes.Add("style", "cursor:pointer;");

我遇到的问题是,当鼠标移过该行时,它会恢复为白色,而不是之前的颜色,这在一半的行中是不同的。我想我可以在为每个“onmouseove”事件替换它之前保存当前的rowcolor,但是如果快速鼠标移动可能会搞砸了,这似乎很昂贵且令人担忧。

我没有看到gridview行的属性告诉我它是否是备用行但是对于rowindex的简单奇数/偶数确定是否最好?

有更好的建议吗?

感谢。

-Dan

3 个答案:

答案 0 :(得分:6)

存储原始样式。然后将样式backgroundColor设置为this.originalstyle

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)  
{  
        if (e.Row.RowType == DataControlRowType.DataRow)  
        {  
            e.Row.Attributes.Add("onmouseover", "this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#ceedfc'");  
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=this.originalstyle");  
            e.Row.Attributes.Add("style", "cursor:pointer;");

答案 1 :(得分:1)

我更喜欢使用CSS来悬停颜色

tr.odd {
  background-color: White;
}
tr.even {
  background-color: #f8f8f8;
}
tr.odd:hover {
  background-color: #f3fcfa;
}
tr.even:hover {
  background-color: #ebf3f1;
}

答案 2 :(得分:0)

使用JQuery:

$(document).ready(function ()
{
    var original = "";

    $("#<%=yourGridViewNameHere.ClientID%> tr:has(td)").hover(function ()
    {
        original = $(this).css("background-color");

        $(this).css("background-color", "Pink");
    }, function ()
    {
        $(this).css("background-color", original);
    });
});

我从here得到的原始答案,我只是根据我的需要调整了一点,如上所示。

享受