这篇文章主要介绍了 js 实现固定显示区域内自动缩放图片的方法, 实例分析了 javascript 操作页面元素及属性的相关技巧, 具有一定参考借鉴价值, 需要的朋友可以参考下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
本文实例讲述了 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 程序设计有所帮助。
来源: