免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3518 | 回复: 2
打印 上一主题 下一主题

如何动态载入一个图片,并设置大小? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-07 19:37 |只看该作者 |倒序浏览
5可用积分
有一个图片容器( <img id="showBox">)和一组图片,鼠标移动到某一图片上时,图片容器加载该图片。如果宽度大于400则等于400,高度大于300则等于300.
例如:
原始图片为500*200,则显示在容器里为400*200
原始图片为200*500,则显示在容器里为200*300
原始图片为100×100(高、宽都没有超过,按原大小显示)



<img id="showBox" />

<img id="img1" src="1.jpg" onmouseover="ShowImage()" />
<img id="img2" src="2.jpg" onmouseover="ShowImage()" />
<img id="img3" src="3.jpg" onmouseover="ShowImage()" />

function ShowImage()
{
    //...
}

最佳答案

查看完整内容

以前自己写的,使用了jQuery,不过改成基本的javascript也很容易对于你的应用类似使用 onXXXXX="toSize(this);"[ 本帖最后由 achun.shx 于 2008-4-8 00:28 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2008-04-07 19:37 |只看该作者
原帖由 荒野狐狸 于 2008-4-7 19:37 发表
有一个图片容器( )和一组图片,鼠标移动到某一图片上时,图片容器加载该图片。如果宽度大于400则等于400,高度大于300则等于300.
例如:
原始图片为500*200,则显示在容器里为400*200
原始图片为200*500,则显 ...

  1.     function toSize(elm,options){
  2.       var jelm=$(elm),w=jelm.width(),h=jelm.height(),width,height;
  3.       /*原来没有这一段,我实例写个伪代码,你自己可以改改*/
  4.       if(!options){
  5.          options.max.width=(w==500)?400:xxxxxxx;
  6.          options.max.height=(h==500)?300:xxxxxxx;
  7.       }
  8.       /********/
  9.       if(options.max){
  10.         options.max.width = options.max.width || w;
  11.         options.max.height= options.max.height || h;
  12.         width = options.max.width<w ? options.max.width : w;
  13.         height = options.max.height<h ? options.max.height : h;
  14.       }
  15.       if(options.min){
  16.         options.min.width = options.min.width || w;
  17.         options.min.height= options.min.height || h;
  18.         width = options.min.width > w ? options.min.width : w;
  19.         height = options.min.height > h ? options.min.height : h;
  20.       }
  21.       height = Math.round(width * h / w);
  22.       jelm.css({width:width + 'px',height:height+'px'});
  23.     }
复制代码

以前自己写的,使用了jQuery,不过改成基本的javascript也很容易对于你的应用类似使用 onXXXXX="toSize(this);"

[ 本帖最后由 achun.shx 于 2008-4-8 00:28 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2008-04-07 22:07 |只看该作者
function ShowImage()
{
var obj=event.srcElement;
document.getElementById("showBox").src=obj.src;
}
至于图片大小问题,设置个
<img id="showBox" style="max-height:300px; max-width:400px;" />
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP