如何使用ImageButtons在GridView TemplateField中保留图像超链接的样式/悬停功能

How to Retain the Styling / Hover Functionality of Image Hyperlinks in a GridView TemplateField using ImageButtons

本文关键字:超链接 样式 功能 悬停 图像 保留 ImageButtons 何使用 GridView TemplateField      更新时间:2023-09-26

在GridView的每一行中(使用TemplateField),我想显示将用于控制该行中数据的图像按钮。然后,我想在用户第一次悬停在GridView行上时交换按钮的图像,然后在用户悬停在特定按钮上时再次交换。

我可以使用CSS和图像超链接轻松地完成悬停功能,但是当使用图像超链接时,我无法引发任何服务器端事件来处理编辑特定行。

在过去,我使用ImageButtons而不是图像超链接。我在ImageButtons中添加了CommandName参数,然后在代码中处理GridView RowCommand

<asp:ImageButton ID="btnSelect" CommandName="select" runat="server" ImageUrl="~/images/iconSelect1.png" />

为了更改悬停时的ImageButton图像,我使用了Javascript:

<asp:ImageButton ID="btnSelect" onmouseover="this.src='../images/iconSelect3.png';" onmouseout="this.src='../images/iconSelect2.png';" runat="server" ImageUrl="~/images/iconSelect1.png" />

然而,在这种情况下,当用户第一次悬停在GridView行本身时,我还需要替换ImageButton图像。

总之,当用户将鼠标悬停在GridView行上时,该行上的ImageButtons将全部将image1替换为image2。然后,当用户悬停在特定的ImageButton上时,其图像将从图像2切换到图像3。

提前感谢您对最佳方法的任何建议。

-------------------------------------编辑---------------------------------------------

不确定这是否是最好的方法,但我使用jQuery找到了一个潜在的解决方案:

<ItemTemplate>
    <div class="gvRow">
        <asp:ImageButton ID="btnSelect" CssClass="btnSelect" runat="server" ImageUrl="~/images/iconSelect1.png" onmouseover="this.src='../images/iconSelect3.png';" onmouseout="this.src='../images/iconSelect2.png';" />
    </div>
</ItemTemplate>
<script type="text/javascript">                                         
    $('.gvRow').hover(
        function () {
            $(this).find(".btnSelect").attr("src", "../images/iconSelect2.png");
        },
        function () {
            $(this).find(".btnSelect").attr("src", "../images/iconSelect1.png");
        }
    );
</script>

到目前为止,这项工作进展顺利,但我愿意接受更好地处理这一问题的建议。

希望这能帮助到其他人。

您的解决方案看起来不错!

为了保持一致性,我会稍微调整一下,以便使用jquery来实现这两种悬停行为,例如,将其添加到现有脚本中:

$('.btnSelect').hover(
    function () {
        $(this).attr("src", "../images/iconSelect3.png");
    },
    function () {
        $(this).attr("src", "../images/iconSelect2.png");
    }
);