js实现固定显示区域内自动缩放图片的方法
作者:qq123 时间:2024-04-16 09:51:35
本文实例讲述了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="dsds.JPG" 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;width:"+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>
希望本文所述对大家的javascript程序设计有所帮助。
标签:js,缩放,图片
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
浅谈python中频繁的print到底能浪费多长时间
2022-01-31 06:24:34
Pygame 精准检测图像碰撞的问题
2022-01-17 17:56:13
python flask 如何修改默认端口号的方法步骤
2021-07-04 16:35:14
解决Pycharm中恢复被exclude的项目问题(pycharm source root)
2023-10-30 11:10:44
![](https://img.aspxhome.com/file/2023/9/120919_0s.jpg)
在laravel中使用Symfony的Crawler组件分析HTML
2023-11-17 18:54:07
Python实现树的先序、中序、后序排序算法示例
2022-12-26 04:00:18
Python3.5以上版本lxml导入etree报错的解决方案
2021-06-25 12:53:16
![](https://img.aspxhome.com/file/2023/6/93856_0s.png)
php session 预定义数组
2023-11-15 01:15:22
启动targetcli时遇到错误解决办法
2023-03-20 05:59:43
Python中非常实用的Math模块函数教程详解
2022-12-08 02:12:49
Python读取配置文件(config.ini)以及写入配置文件
2021-01-28 14:02:39
![](https://img.aspxhome.com/file/2023/0/115860_0s.jpg)
SQLServer2005安装提示服务无法启动原因分析及解决
2024-01-16 03:02:26
![](https://img.aspxhome.com/file/2023/6/100006_0s.png)
Vue3兄弟组件传值之mitt的超详细讲解
2023-07-02 16:56:04
Python 调用PIL库失败的解决方法
2023-01-25 02:47:08
Python二进制转化为十进制数学算法详解
2021-11-09 19:45:20
PyQt5中QTimer定时器的实例代码
2021-06-01 07:28:54
![](https://img.aspxhome.com/file/2023/7/93797_0s.png)
python如何查看微信消息撤回
2023-07-31 23:18:09
![](https://img.aspxhome.com/file/2023/1/117961_0s.png)
Python计算字符宽度的方法
2021-02-13 20:25:28
Python从csv文件中读取数据及提取数据的方法
2021-01-26 07:12:44
![](https://img.aspxhome.com/file/2023/7/114507_0s.jpg)
安全校验Session验证码并避免绕开验证码攻击
2022-06-30 20:15:41