js 实现网页图片缩略图按比例缩放

本文介绍了一段JavaScript代码,该代码可在图片加载完成后自动按比例调整图片大小,避免图片拉伸导致的模糊现象,适用于网页中需要统一图片显示效果的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     在处理网页图片缩略图时,很难保证图片统一大小,直接设置图片大小又会导致图片拉伸,造成图片模糊,本文介绍的代码可以在图片加载完成后自动按比例调整图片大小。

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageAutoZoom.aspx.cs" Inherits="UI_ImageAutoZoom" %>

 

<!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 runat="server">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

    <title>js 实现网页图片按比例缩放-by wangtao</title>

    <script type="text/javascript" src="../Misc/Js/Core/Jquery.js"></script>

</head>

<body>

<script type="text/javascript">

function ImageAutoZoom(Img,FitWidth,FitHeight)

{

  var image=new Image();

  image.src=Img.src;

  if(image.width>0 && image.height>0) 

  {

    if(image.width/image.height>= FitWidth/FitHeight)

    {

     if(image.width>FitWidth) 

     {

       Img.width=FitWidth;

       Img.height=(image.height*FitWidth)/image.width; 

     }

     else if(image.hight>FitHeight)

     {

       Img.height=FitHeight;

       Img.width=(image.width*FitHeight)/image.height; 

     }

     else

     {

      Img.width=FitWidth;

      Img.height=FitHeight;

     }

    }

  }

</script>

 

    <form id="ImageAutoZoomform" runat="server">

    <div>

    <img  src="../Misc/Image/Test/war3.jpg" height="200" width="200" alt="按比例缩放图片" onload="ImageAutoZoom(this,200,200)" />

    </div>

    </form>

</body>

</html>

   因为当图片太大的时候,页面会造成一种拉动,所以最好设一下height,width这样可以减少拉动的范围。
虽然这个没有很大的技术含量,但是很实用,大部分网站用到图片的地方,多多少少都会涉及到的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值