>  기사  >  웹 프론트엔드  >  JS를 사용하여 이미지 캐러셀을 구현하는 예

JS를 사용하여 이미지 캐러셀을 구현하는 예

韦小宝
韦小宝원래의
2018-01-15 11:27:422732검색

아래 편집기에서는 JS를 사용하여 이미지 캐러셀(앞뒤, 끝에서 끝까지)을 구현하는 예를 보여줍니다. 편집자는 꽤 좋다고 생각합니다. 이제 js 소스 코드를 공유하고 참고하겠습니다. js에 관심있으신 분들은 저를 따라오셔서 구경해보세요

최근에 여러 인터뷰에 갔는데, 마지막으로 이런 질문을 받았는데, 당시엔 end to를 어떻게 연결해야 할지 몰랐습니다. 돌아와서 조사를 좀 했는데 드디어 해냈습니다. 할 말은 없지만 코드만 보세요

코드는 이미 사진 캐러셀 기능을 작성한 사람을 나타냅니다(다시 한번 감사드립니다). , 그런데 시작과 끝을 연결하는 기능은 없습니다. 이를 바탕으로 시작과 끝을 추가했습니다.

효과는 다음과 같습니다.

<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>图片轮播</title>
 <style type="text/css">
 body,p,ul,li,a,img{margin: 0;padding: 0;}
 ul,li{list-style: none;}
 a{text-decoration: none;}
 #wrapper{
  position: relative;
  margin: 30px auto; /* 上下边距30px,水平居中 */
  width: 400px;
  height: 200px;
 }
 #banner{
  position:relative;
  width: 400px;
  height: 200px;
  overflow: hidden;
 }
 .imgList{
  position:relative;
  width:2000px;
  height:200px;
  z-index: 10;
  overflow: hidden;
 }
 .imgList li{float:left;display: inline;}
 #prev,
 #next{
  position: absolute;
  top:80px;
  z-index: 20;
  cursor: pointer;
  opacity: 0.2;
  filter:alpha(opacity=20);
 }
 #prev{left: 10px;}
 #next{right: 10px;}
 #prev:hover,
 #next:hover{opacity: 0.5;filter:alpha(opacity=50);}

</style>
</head>
<body>
 <p id="wrapper"><!-- 最外层部分 -->
 <p id="banner"><!-- 轮播部分 -->
  <ul class="imgList"><!-- 图片部分 -->
  <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><img src="./img/1.jpg" width="400px" height="200px" alt="1"></a></li>
  <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><img src="./img/2.jpg" width="400px" height="200px" alt="2"></a></li>
  <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><img src="./img/3.jpg" width="400px" height="200px" alt="3"></a></li>
  <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><img src="./img/4.jpg" width="400px" height="200px" alt="4"></a></li>
  <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><img src="./img/5.jpg" width="400px" height="200px" alt="5"></a></li>
 </ul>
 <img src="./img/prev.png" width="40px" height="40px" id="prev">
 <img src="./img/next.png" width="40px" height="40px" id="next">
</p>
</p>
<script type="text/javascript" src="./js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var curIndex = 0, //当前index
 imgLen = $(".imgList li").length; //图片总数
$(".imgList").css("width", (imgLen+1)*400+"px");
// 定时器自动变换3秒每次
var autoChange = setInterval(function(){
 if(curIndex < imgLen-1){
  curIndex ++;
 }else{
  curIndex = 0;
 }
 //调用变换处理函数
 changeTo(curIndex);
},3000);

//左箭头滑入滑出事件处理
$("#prev").hover(function(){
 //滑入清除定时器
 clearInterval(autoChange);
}, function(){
 //滑出则重置定时器
 autoChangeAgain();
});

//左箭头点击处理
$("#prev").click(function(){
 //根据curIndex进行上一个图片处理
 // curIndex = (curIndex > 0) ? (--curIndex) : (imgLen - 1);
 if (curIndex == 0) {
  var element = document.createElement("li");
  element.innerHTML = $(".imgList li")[imgLen - 1].innerHTML;
  // $(".imgList li")[imgLen - 1].remove();
  $(".imgList").prepend(element);
  $(".imgList").css("left", -1*400+"px");
  changeTo(curIndex);
  curIndex = -1;
 } else if (curIndex == -1) {
  $(".imgList").css("left", -(imgLen-1)*400+"px");
  curIndex = imgLen-2;
  $(".imgList li")[0].remove();
  changeTo(curIndex);
 } else {
  --curIndex;
  changeTo(curIndex);
 }

});

//右箭头滑入滑出事件处理
$("#next").hover(function(){
 //滑入清除定时器
 clearInterval(autoChange);
}, function(){
 //滑出则重置定时器
 autoChangeAgain();
});
//右箭头点击处理
$("#next").click(function(){
 // curIndex = (curIndex < imgLen - 1) ? (++curIndex) : 0;
 console.log(imgLen);
 if (curIndex == imgLen-1) {
  var element = document.createElement("li");
  element.innerHTML = $(".imgList li")[0].innerHTML;
  // $(".imgList li")[0].remove();
  $(".imgList").append(element);
  ++curIndex;
 } else if (curIndex == imgLen) {
  curIndex = 0;
  $(".imgList").css("left", "0px");
  $(".imgList li")[imgLen].remove();
  curIndex++;
 } else {
  ++curIndex;
 }
 changeTo(curIndex);
});

//清除定时器时候的重置定时器--封装
function autoChangeAgain(){
 autoChange = setInterval(function(){
  if(curIndex < imgLen-1){
   curIndex ++;
  }else{
   curIndex = 0;
  }
 //调用变换处理函数
 changeTo(curIndex);
 },3000);
}


function changeTo(num){
 var goLeft = num * 400;
 $(".imgList").animate({left: "-" + goLeft + "px"},500);
}
</script>
</body>
</html>

위 JS를 사용하여 이미지 캐러셀을 구현한 예시는 모두 에디터가 공유한 내용이므로 참고가 되셨으면 좋겠습니다! !

관련 권장 사항:

JavaScript 정의 함수의 세 가지 구현 방법

JavaScript의 다중 상속 예제에 대한 자세한 설명

가장 완벽한 JavaScript 학습 요약

위 내용은 JS를 사용하여 이미지 캐러셀을 구현하는 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.