js限制图片大小、点击放大图片、点击在新开页面显示

缩放图片到合适大小
        function ResizeImages() {
            var myimg, oldwidth, oldheight;
            var maxwidth = 400;
            var maxheight = 400
            var imgs = document.getElementsByTagName('img');  //获取页面图片  这里使用document过去

            for (i = 0; i < imgs.length; i++) {
                myimg = imgs[i];

                if (myimg.width > myimg.height) {
                    if (myimg.width > maxwidth) {
                        oldwidth = myimg.width;
                        myimg.height = myimg.height * (maxwidth / oldwidth);
                        myimg.width = maxwidth;
                    }
                } else {
                    if (myimg.height > maxheight) {
                        oldheight = myimg.height;
                        myimg.width = myimg.width * (maxheight / oldheight);
                        myimg.height = maxheight;
                    }
                }
            }
        }
点击放大、再点击恢复

点击放大两倍 再点击恢复正常大小
            var flag = true;//状态true为正常的状态,false为放大的状态
            $("#img").click(function () {
                var imgH,//图片的高度
                    imgW,//图片的宽度
                    img = document.getElementsByTagName('img')[0];//图片元素
                //图片点击事件
                imgH = img.height; //获取图片的高度
                imgW = img.width; //获取图片的宽度
                if (flag) {
                    //图片为正常状态,设置图片宽高为现在宽高的2倍
                    flag = false;//把状态设为放大状态
                    img.height = imgH * 2;
                    img.width = imgW * 2;
                } else {
                    //图片为放大状态,设置图片宽高为现在宽高的二分之一
                    flag = true;//把状态设为正常状态
                    img.height = imgH / 2;
                    img.width = imgW / 2;
                }
            });

点击在新页面打开浏览原图

//在新页面打开浏览
            $("#img").click(function () {
                var src = $("#img").attr("src");
                window.open(src);
            });
  

posted on 2018-11-15 11:52  4job  阅读(920)  评论(0编辑  收藏  举报

导航