jQuery实现等比例缩放大图片

来源:互联网 发布:云计算的应用实例 编辑:程序博客网 时间:2024/05/02 21:37

在页面布局时,有时会遇到大图片将页面容器撑大,超出规定区域,

这时我们就需要将图片按比例缩放,让大图片自适应页面布局。


查看演示http://itmyhome.com/jquery_image_scaling/


1、页面中有如下图片

<img alt="leaf" src="img/leaf.jpg"> 

2、使用jQuery将图片缩放

<script type="text/javascript">window.onload = function() {var w = 500;//设置最大宽度,也可根据img的外部容器 而动态获得,比如:$("#demo").width();$("img").each(function() {//如果有很多图片,使用each()遍历 var img_w = $(this).width();//图片宽度 var img_h = $(this).height();//图片高度 if (img_w > w) {//如果图片宽度超出指定最大宽度 var height = (w * img_h) / img_w; //高度等比缩放 $(this).css( {"width" : w,"height" : height});//设置缩放后的宽度和高度 }});}$(document).ready(function() {//就本例而言 不要用 jQuery中的ready 你懂的...})</script>

作者:itmyhome


9 0