鼠标悬停图片显示大图效果的JavaScript实现

作者:代码拾荒时间:2026-10-27 08:41:16浏览:477

本文提供了一段JavaScript代码,用于实现鼠标悬停在缩略图上时显示对应大图的功能。代码包含尺寸限制逻辑,确保大图在指定最大宽高(400x300)内自适应显示,并通过简单的DOM操作控制大图的显示与隐藏。

JavaScript实现图片悬停显示大图功能

实现图片悬停显示大图及隐藏大图功能的JavaScript代码如下:

具体代码实现如下:

<script type="text/javascript">
// 定义显示图片的函数
function over(imgid, obj, imgbig)
   {
// 设定大图显示的最大尺寸,按4:3比例限制为400x300
maxwidth=400;
maxheight=300;
// 执行显示逻辑
 obj.style.display="";
 imgbig.src=imgid.src;
 // 1、如果宽和高都超过限制值,比较超出部分的大小,超出较多的那个维度设为最大值,另一维度按后续策略处理
 // 2、如果宽超过限制而高未超,则将宽设为最大值
 // 3、如果宽未超而高超过限制,则将高设为最大值
 if(img.width>maxwidth&&img.height>maxheight)
 {
 pare=(img.width-maxwidth)-(img.height-maxheight);
 if(pare>=0)
 img.width=maxwidth;
 else
 img.height=maxheight;
 }
 else if(img.width>maxwidth&&img.height<=maxheight)
 {
 img.width=maxwidth;
 }
 else if(img.width<=maxwidth&&img.height>maxheight)
 {
 img.height=maxheight;
 } 
 }
// 定义隐藏图片的函数
 function out()
 {
document.getElementById('divImage').style.display="none";
 }
</script>

用于展示小图的HTML元素及对应大图的容器结构如下:

具体HTML结构代码如下:

<img id="img" src="https://www.jb51.net/images/logo.gif" onmouseover="over(img,divImage,imgbig);" onmouseout="out()" width="100" alt="" height="100" />
<%-- 用于显示大图区域的注释 --%>
<div id="divImage" style="display: none; left: 120px;top:5px; position: absolute">
<img id="imgbig" src="https://www.jb51.net/images/logo.gif" alt="预览" />
</div>
作者最新文章