[原创]javascript 指定区域内图片等比例缩放实现代码

  作者:bea

整合篇,欢迎转载。 代码如下: 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/(t
整合篇,欢迎转载。


代码如下:


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+'</a>'
}
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,下面是测试代码。



<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+'</a>'
}
else{
c[i].title="在新窗口打开图片";
c[i].onclick=function(e){window.open(this.src)}
}
}
}
}
window.onload=function(){
controlImg(document.getElementById("dxy"),300,300);
}
</script>
<body>
<img src="http:///images/logo.gif" />
下面是要控制的区域。
<div id="dxy">
原图 <center><img alt='photoshop 图片调色教程 苍白皮肤的冷酷美女' height="972" width="648" src="http://files./file_images/photoshop/200910/200910241416206868.jpg" /></center>
  教程图层:
  一 打开原图 复制一层
  二 执行图层<新建调整图层<色相/饱和度 参数不讲解
  三 执行图层<新建调整图层<曲线
  四 去色 然后降低不透明度
  五 执行图层<新建调整图层<亮度/对比度 <center><img alt='photoshop 图片调色教程 苍白皮肤的冷酷美女' height="538" width="800" src="http://files./file_images/photoshop/200910/200910241416206969.jpg" /></center>
</div>
这下面是不需要控制的区域,大家可以参考下。
原图 <center><img alt='photoshop 图片调色教程 苍白皮肤的冷酷美女' height="972" width="648" src="http://files./file_images/photoshop/200910/200910241416206868.jpg" /></center>
  教程图层:
  一 打开原图 复制一层
  二 执行图层<新建调整图层<色相/饱和度 参数不讲解
  三 执行图层<新建调整图层<曲线
  四 去色 然后降低不透明度
  五 执行图层<新建调整图层<亮度/对比度 <center><img alt='photoshop 图片调色教程 苍白皮肤的冷酷美女' height="538" width="800" src="http://files./file_images/photoshop/200910/200910241416206969.jpg" /></center>
</body>




[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);

 }


  如此定义后,其中的图片宽就不会超过600,高不超过450,并按原比例值缩小!


有用  |  无用

猜你喜欢