gridview显示图片并实现点击图片放大缩小

一、创建一个gridview控件,并添加列。

其中ImageField就是显示图片的列,属性DataImagteUrlField绑定为图片的路径,也就是数据库存储图片路径的字段名。

二、创建一个用来显示大图片的div 以及Img控件。以及css样式、js。

Html

 <div id="Show_img_Max" onclick="divClick()">
            <div>
                <img src="" class="Show_imgStyle" />
            </div>
 </div>

css样式

* {
            margin: 0;
            padding: 0;
        }

        html, body {
            width: 100%;
            height: 100%;
        }

        #form1 > .divMain {
            margin: 0 auto;
            padding-top: 150px;
            width: 800px;
            height: 500px;
            text-align: center;
        }

        #Show_img_Max {
            position: absolute;
            top: 1px;
            display: none;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

            #Show_img_Max > div {
                margin: 100px auto;
                width: 550px;
                height: 350px;
            }

            #Show_img_Max .Show_imgStyle {
                width: 550px;
                height: 350px;
            }

js

  function CellClick(ImgUrl) {
            $(".Show_imgStyle").attr("src", ImgUrl);
            $("#Show_img_Max").css("display", "block");
        }
        function divClick() {
            $("#Show_img_Max").css("display", "none");
        }

三、添加一个gridview行数据绑定后激发事件(RowDataBound),在该事件写代码。

 protected void grdview_test_RowDataBound(object sender, GridViewRowEventArgs e)
    {
       //判断是否为数据行
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //设置图片的宽、高度
            (e.Row.Cells[3].Controls[0] as Image).Width = 70;
            (e.Row.Cells[3].Controls[0] as Image).Height = 50;
            //获取当前行的图片路径
            string ImgUrl = (e.Row.Cells[3].Controls[0] as Image).ImageUrl;
            //给带图片的单元格添加点击事件
            e.Row.Cells[3].Attributes.Add("onclick", e.Row.Cells[3].ClientID.ToString() 
                +".checked=true;CellClick('" + ImgUrl+ "')");
        }
    }

四、数据方面就自己添加了。效果图如下:

显示:

点击图片后:

然后点击其他地方或者图片就恢复原状。

由于我是第一次写博客,所以有什么不好的地方请指出,我会努力改正,相信以后会写的更好,谢谢。

猜你喜欢

转载自blog.csdn.net/qq_41987694/article/details/81094583