介紹:這里是我使用了計時器的方式實作圖片每隔幾秒切換然后添加了兩個按鈕用于上一張和下一張的切換
1,匯入jQuery檔案
<script src="jquery-3.5.1.js"></script>
2,設定圖片的樣式
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 300px;
height: 300px;
border: 2px solid red;
}
#box img{
position: absolute;
display: none;
}
#box :first-child{
display: block;
}
.page{
list-style: none;
display: flex;
width: 300px;
justify-content: space-around;
}
.page li{
border: 1px solid red;
border-radius: 50%;
width: 20px;
height: 20px;
text-align: center;
}
.active{
background: red;
}
</style>
<script src="./jquery.js"></script>
</head>
<body>
<div id="box">
<img src="./img/1.jpg" alt="">
<img src="./img/2.jpg" alt="">
<img src="./img/3.jpg" alt="">
<img src="./img/4.jpg" alt="">
</div>
<ul class="page" id="page" >
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<button id="next">下一張</button>
<button id="prev">上一張</button>
3 進行圖片的輪播實作方式
/*
絕對定位 -- 摞起來
通過下標 -- 顯示當前 --其他兄弟 隱藏
*/
<script>
var index=0;
// 移動方法
function move(){
index++;
if (index>=$("#box img").length) {
index=0;
}
$("#box img").eq(index).show().siblings().hide();
$("#page li").eq(index).addClass("active").siblings().removeClass("active");
}
//計時器的實作方法
var t=setInterval(move,2000);
//滑鼠移動到圖片會停止離開繼續輪播
$("#box").hover(function(){
clearInterval(t)
},function(){
t=setInterval(move,2000)
})
$("#page li").click(function(){
index= $(this).index() ;
$("#box img").eq(index).show().siblings().hide();
$("#page li").eq(index).addClass("active").siblings().removeClass("active");
})
//下一張的點擊
$("#next").click(function(){
move();
})
//上一張的點擊
$("#prev").click(function(){
index--;
// 判斷如果下標超過固有圖片的數量時,從頭開始輪播
if (index<0) {
index=$("#box img").length-1;
}
$("#box img").eq(index).show().siblings().hide();
$("#page li").eq(index).addClass("active").siblings().removeClass("active");
})
</script>
各位兄臺路過點贊 抱拳!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/240548.html
標籤:其他
上一篇:阿里云-云開發平臺入門篇——靜態網站的全生命周期實戰
下一篇:前端常用網站匯總
