文章类型: JAVASCRIPT
关键词: JavaScript,JS,实现,图片,等比例,缩放
内容摘要:

用JavaScript实现图片等比例缩放

2015/7/29 12:00:12    来源:apple    阅读:

把下面的函数放在页面中(任意位置都可以):

function resizeimg(ImgD,iwidth,iheight) { 
       var image=new Image(); 
       image.src=ImgD.src; 
  
     if(image.width>0 && image.height>0){   
  
        if(image.width/image.height>= iwidth/iheight){   
  
           if(image.width>iwidth){   
                 ImgD.width=iwidth; 
  
                 ImgD.height=(image.height*iwidth)/image.width;   
  
           }else{ 
                    ImgD.width=image.width;   
  
                  ImgD.height=image.height;   
                  }   
  
               ImgD.alt=image.width+"×"+image.height;   
          } 
  
        else{ 
                  if(image.height>iheight){   
  
                       ImgD.height=iheight;   
  
                       ImgD.width=(image.width*iheight)/image.height;   
  
                }else{   
                          ImgD.width=image.width;   
                          ImgD.height=image.height;   
  
                     }   
  
                ImgD.alt=image.width+"×"+image.height;   
              } 
       ImgD.style.cursor= "pointer"; //改变鼠标指针 
       ImgD.onclick = function() { window.open(this.src);} //点击打开大图片 
      if (navigator.userAgent.toLowerCase().indexOf("ie") > -1) { //判断浏览器,如果是IE 
        ImgD.title = "请使用鼠标滚轮缩放图片,点击图片可在新窗口打开"; 
        ImgD.onmousewheel = function img_zoom() //滚轮缩放 
        { 
            var zoom = parseInt(this.style.zoom, 10) || 100; 
  
            zoom += event.wheelDelta / 12;   
            if (zoom> 0) this.style.zoom = zoom + "%";   
            return false; 
        } 
       } else { //如果不是IE 
              ImgD.title = "点击图片可在新窗口打开"; 
           } 
      } 
  }

在需要实现等比缩放的图片上加上onload语句,图片装载时初始化大小。

  具体实现代码如下:

   <img id="myImage" alt="" src="images/dive.jpg" onload="javascript:resizeimg(this,this.width,this.height)" />

<img name="" src="" onload="javascript:resizeimg(this,100,200)">
↑ 上一篇文章:类型“System.Web.UI.UpdatePanel”不具有名为xxx的公共属性 解决方法 关键词:类型,System,Web,UI,UpdatePanel.. 发布日期:2015/7/29 11:57:51
↓ 下一篇文章:ASP.NET前台javascript与c#后台代码调用 关键词:ASP.NET,前台,javascript,c#,后台代.. 发布日期:2015/7/29 12:01:50
相关文章:
全面兼容ie[6-11]、火狐、Chrome、opera、maxthon3、360浏览器的js本地图片预览 关键词:全面,兼容,ie,火狐,Chrome,opera,maxthon3,360浏览器,js,Java.. 发布日期:2015-07-14 16:45
js判断是否为空(二) 关键词:js,javascript,判断,空,Null,NULL,null,字符串,实例 发布日期:2015-07-29 14:01
js判断为空null与字符串为空实例 关键词:js,javascript,判断,空,Null,NULL,null,字符串,实例 发布日期:2015-07-29 14:00
相关目录:.NET软件开发JAVASCRIPTANDROID
我要评论
正在加载评论信息......