JavaScript实现网页图片等比例缩放


文中代码允许在IE、FireFox下等比例缩放图片。同时,在IE下,能够通过鼠标的滚轮对图片进行动态缩放。具体可以参考mg-photo-agent插件。

  1. //图片按比例缩放,可输入参数设定初始大小
  2. function resizeimg(ImgD,iwidth,iheight) {
  3.      var image=new Image();
  4.      image.src=ImgD.src;
  5.      if(image.width>0 && image.height>0){
  6.         if(image.width/image.height>= iwidth/iheight){
  7.            if(image.width>iwidth){
  8.                ImgD.width=iwidth;
  9.                ImgD.height=(image.height*iwidth)/image.width;
  10.            }else{
  11.                   ImgD.width=image.width;
  12.                   ImgD.height=image.height;
  13.                 }
  14.                ImgD.alt=image.width+"×"+image.height;
  15.         }
  16.         else{
  17.                 if(image.height>iheight){
  18.                        ImgD.height=iheight;
  19.                        ImgD.width=(image.width*iheight)/image.height;
  20.                 }else{
  21.                         ImgD.width=image.width;
  22.                         ImgD.height=image.height;
  23.                      }
  24.                 ImgD.alt=image.width+"×"+image.height;
  25.             }
  26.      ImgD.style.cursor= "pointer"; //改变鼠标指针
  27.      ImgD.onclick = function() { window.open(this.src);} //点击打开大图片
  28.     if (navigator.userAgent.toLowerCase().indexOf("ie") > -1) { //判断浏览器,如果是IE
  29.       ImgD.title = "请使用鼠标滚轮缩放图片,点击图片可在新窗口打开";
  30.       ImgD.onmousewheel = function img_zoom() //滚轮缩放
  31.       {
  32.           var zoom = parseInt(this.style.zoom, 10) || 100;
  33.           zoom += event.wheelDelta / 12;
  34.           if (zoom> 0) this.style.zoom = zoom + "%";
  35.           return false;
  36.       }
  37.      } else { //如果不是IE
  38.             ImgD.title = "点击图片可在新窗口打开";
  39.          }
  40.     }
  41. }

该代码的使用方法如下:

  1. <img name="" src="" onload="javascript:resizeimg(this,100,200)">

感谢您的关注。您现在可以 留言(0)留下通告地址



Leave a Reply

Note: Any comments are permitted only because the site owner is letting you post, and any comments will be removed for any reason at the absolute discretion of the site owner.

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image