首页 > web前端 > js教程 > 正文

javascript 指定区域内图片等比例缩放实现代码 脚本之家整合版[原创]_图象特效

WBOY
发布: 2016-05-16 18:43:33
原创
1200 人浏览过

脚本之家整合篇,欢迎转载。

复制代码 代码如下:

function controlImg(ele,w,h){
var c=ele.getElementsByTagName("img");
for(var i=0;ivar w0=c[i].clientWidth,h0=c[i].clientHeight;
var t1=w0/w,t2=h0/h;
if(t1>1||t2>1){
c[i].width=Math.floor(w0/(t1>t2?t1:t2));
c[i].height=Math.floor(h0/(t1>t2?t1:t2));
if(document.all){
c[i].outerHTML='' c[i].outerHTML ''
}
else{
c[i].title="在新窗口打开图片";
c[i].onclick=function(e){window.open(this.src)}
}
}
}
}
window.onload=function(){
controlImg(document.getElementById("content"),670,980);
}

以前就需要这样的代码,但因为具体的思路不是和很清楚,今天在blueidea看到的文章,特整理下。
指定区域内的,一般用于控制内容部分的图片,可通过controlImg(document.getElementById("content"),670,980); 中的content,下面是测试代码。

[Ctrl A 全选 注:如需引入外部Js需刷新才能执行
]


下面是用css expression实现的方法会增加客户端的负荷,建议用js的
假设有一个id为test的div,如何控制其内的图片不会撑呢?
  如下定义CSS即可: 代码如下:


  #test IMG{
  border:0;
  margin:0;
  padding:0;
  max-width:600px;
  width:expression(this.width>600?"600px":this.width);
  max-height:450px;
  height:expression(this.height>450?"450px":this.height);
  }

<script> //============================== function controlImg(ele,w,h){ var c=ele.getElementsByTagName("img"); for(var i=0;i<c.length;i++){ var w0=c[i].clientWidth,h0=c[i].clientHeight; var t1=w0/w,t2=h0/h; if(t1>1||t2>1){ c[i].width=Math.floor(w0/(t1>t2?t1:t2)); c[i].height=Math.floor(h0/(t1>t2?t1:t2)); if(document.all){ c[i].outerHTML='<a href="'+c[i].src+'" target="_blank" title="在新窗口打开图片">'+c[i].outerHTML+'' } else{ c[i].title="在新窗口打开图片"; c[i].onclick=function(e){window.open(this.src)} } } } } window.onload=function(){ controlImg(document.getElementById("dxy"),300,300); } </script>  如此定义后,其中的图片宽就不会超过600,高不超过450,并按原比例值缩小!
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!