基于jQuery实现点击箭头切换图片的简单示例

作者:开源拾贝时间:2026-10-27 06:33:27浏览:470

本文介绍如何使用jQuery实现点击左右箭头切换图片的功能。通过定义图片数组、获取图片位置并动态调整箭头显示,结合HTML结构完成交互。代码包含JS逻辑与HTML布局,适合前端初学者参考学习。

jQuery实现图片切换功能示例

操作流程如下:



(1) 准备素材(包含左右方向箭头图标及若干示例图片)



(2) JS(基于jquery)实现代码如下:


具体代码:

 
<script type="text/javascript" src="JS/jquery-1.4.4.js"></script>
<script type="text/javascript">
var picPath = new Array();
picPath.push("Images/chuang_yhb.jpg");
picPath.push("Images/dong_wgx.jpg");
picPath.push("Images/gao_xsg.jpg");
var index = 0;
$(function() {
var top = $("#img1").offset().top;
var left = $("#img1").offset().left;
var height = $("#img1").height();
var width = $("#img1").width();
$("#img1").attr({ "src": picPath[index] });
$("#img1").parent().hover(function() {
//显示左右方向箭头
$("#leftArrow").show();
$("#rightArrow").show();
$("#leftArrow").css({ "left": left - 10, "top": top + (height / 2) });
$("#rightArrow").css({ "left": left + width, "top": top + (height / 2) });
}, function() {
//隐藏左右方向箭头
$("#leftArrow").hide();
$("#rightArrow").hide();
}); 
$("#leftArrow").click(function() {
if (index > 0) {
$("#img1").attr({ "src": picPath[--index] });
} 
}); 
$("#rightArrow").click(function() {
if (index < picPath.length) {
$("#img1").attr({ "src": picPath[++index] });
} 
}); 
}); 
</script>

(3) Html结构如下:


具体代码:

 
<div>
<img id="img1" alt="Show Pictures" style="margin-left:100px;" />
<img id="leftArrow" alt="Left Arrow" src="Images/arrowa.jpg" style="position:absolute;display:none;width:50px;height:35px;z-index:99" />
<img id="rightArrow" alt="Right Arrow" src="Images/arrowb.jpg" style="position:absolute;display:none;width:50px;height:35px;z-index:99" />
</div>


下面再附一个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=gb2312" /> <title>无标题文档</title> <style type="text/css"> <!-- *{ margin:0; padding:0} #imgslide{ margin:100px auto; width:550px; position:relative;-moz-user-select:none } #imgslide img{ width:550px} #imgslide #pre{ position:absolute; display:block; height:100%; background:#003366;filter:Alpha(Opacity=0);opacity:0; left:0; top:0; z-index:2; width:50%; cursor:url(http://s.xnimg.cn/imgpro/arrow/pre.cur),auto; } #imgslide #next{ position:absolute;z-index:2; display:block; background:#00CC99;filter:Alpha(Opacity=0);opacity:0; height:100%;width:50%; top:0; right:0; cursor:url(http://s.xnimg.cn/imgpro/arrow/next.cur), auto;} #intro{ padding:5px 8px; line-height:1.6; font-size:12px; color:#333; background:#333333; color:#fff} --> </style></head> <body> <div id="imgslide"><span id="pre" ></span> <span id="next" ></span><img src="/uploads/20261027/bfe4f91cb1482ffc40714ceac31e313149d76ad0f3aec0eee2da4c0de4219d54.jpg" /> <div id="intro"> </div> </div>  </body> </html> 

[Ctrl+A 全选 注:引入外部Js需再刷新一下页面才能执行]

作者最新文章