zoukankan      html  css  js  c++  java
  • js控制图片自动缩放,实现铺满盒子,不变形,完全局中

    此js一般用于控制图片铺满盒子,但是比例不变,并且绝对局中
    原理:判断图片的高宽与盒子高宽的大小的关系,然后通过比例来控制图片的缩放及定位


    <!
    DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> #img{ width:600px; height:400px; position:relative; overflow:hidden; background:#996699;} </style> </head> <body> <div id="img"><img src="images/test_01.png" onload="resize_img(this,600,400)" /></div> </body> </html> <script type="text/javascript"> function resize_img(pic,w,h){//参数 var re_new_size=function(r){ //根据比率重新计算宽度 return {w:pic.width/r,h:pic.height/r}; }; var re_offset=function(n){ //根据新的宽高度返回偏移量 return {off_l:(n.w-w)*0.5,off_t:(n.h-h)*0.5}; }; var re_position=function(o,n){ //重新定位图片 pic.style.cssText="position:absolute;top:"+-o.off_t+"px;left:"+-o.off_l+"px;"+n.w+"px;height:"+n.h+"px;"; }; var execute=function(rate){//总执行函数 var new_size=re_new_size(rate), offset_new=re_offset(new_size); re_position(offset_new,new_size); }; //判断变量 var rate_of_w=pic.width/w, rate_of_h=pic.height/h, rate; if(rate_of_w>=1){ //图片宽度大于显示区域宽度 if(rate_of_h>=1){ //且图片高度大于显示区域高度 rate=Math.min(rate_of_w,rate_of_h); }else{ //图片高度小于显示区域 rate=pic.height/h; } }else{ //图片宽度小于显示区域宽度 if(rate_of_h>=1){ //且图片高度大于显示区域高度 rate=pic.width/w; }else{ //图片高度小于显示区域高度 rate=Math.min(rate_of_w,rate_of_h); } } execute(rate); //执行入口 } </script>
  • 相关阅读:
    ghm一般规则
    沃尔玛强推RFID内外交困:供应商阳奉阴违
    电子商务物流解决方案
    database url
    物流中新技术应用的必要性
    美国物流管理协会更名标志全球物流进入供应链时代
    业内专家激辩物流挑战与机遇
    问的智慧
    调查报告:2003年物流信息化现状及挑战
    查找在菜单里提交的报表所在职责
  • 原文地址:https://www.cnblogs.com/LChenglong/p/6672702.html
Copyright © 2011-2022 走看看