首先把基本頁面做好
html代碼如下:
<div id = 'banner'>
<div id="carousel">
<img src="../img/1.jpg" alt="" style="display: block;">
<img src="../img/2.jpg" alt="">
<img src="../img/3.jpg" alt="">
<img src="../img/4.jpg" alt="">
<img src="../img/5.jpg" alt="">
</div>
<div id="left"><</div>
<div id="right">></div>
<ul class="slide-nav">
<li class="on"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
其中類名和id自己隨意取,你這里只需要把圖片路徑改一下就好了,
以下是css代碼:
*{
margin: 0;
padding: 0;
}
ul li{
list-style: none;
}
#banner{
width: 590px;
height: 470px;
border: groove 2px;
margin: 50px auto;
position: relative;
}
#carousel{
width: 100%;
height: 100%;
}
#carousel img{
position: absolute;
display: none;
}
#left,#right{
padding: 10px 6px;
background-color: black;
color: white;
position: absolute;
top:50%;
cursor: pointer;
}
#right{
right: 0;
}
.slide-nav{
width: 200px;
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.slide-nav li{
width: 20px;
height: 20px;
background-color: white;
float: left;
margin-right: 5px;
border-radius: 50%;
cursor: pointer;
}
.slide-nav li.on{
background-color: red;
}
好了進入今天主題,前面廢話有點多了哈,
話不多說,jQuery代碼如下:
(首先引入jQuery)
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
推薦大家一個:BootCDN
BootCDN 是 貓云 聯合 Bootstrap 中文網 共同支持并維護的前端開源專案免費 CDN 服務
我就是從這里引入的jQuery
以下是正式代碼:
//獲取所有圖片
var img = $("img")
var len = $("img").length
var lis = $(".slide-nav li")
// 設定截流變數,防止點擊過快問題
let isMove = true
//設定當前索引currentIndex,下個索引 nextIndex
let currentIndex = 0 , nextIndex = 1;
// 輪播函式
function move(){
if(isMove){
isMove = false
img.eq(currentIndex).fadeOut(1000,function(){
// 淡出結束后把isMove變回true
isMove = true
});
img.eq(nextIndex).fadeIn(1000,function(){
// 淡入結束后把isMove變回true
isMove = true
});
$('li').eq(nextIndex).addClass('on').siblings().removeClass('on')
currentIndex = nextIndex
nextIndex += 1
if(nextIndex >= len) {
nextIndex = 0
}
}
}
// 全域標記
let timer
// 設定輪播
function auto() {
timer = setInterval(move,3000)
}
// 啟動輪播
auto()
// 滑鼠移入/移出暫停/繼續輪播
$('#banner').hover(function () {
clearInterval(timer)
},function(){
auto()
})
// 點擊箭頭效果
$("#right").click(function(){
move()
})
$("#left").click(function(){
nextIndex = currentIndex - 1
if(nextIndex < 0){
nextIndex = len -1
}
move()
})
// 小圓點效果
lis.click(function(){
nextIndex = $(this).index()
move()
})
因為jQuery有個佇列問題,就是連續點擊同個事件,當點擊的事件
未完成時,再點擊該事件時,后一個事件就會排在前一個事件后面
按順序執行,所以在該案例中,如果你快速的點擊切換按鈕(包括
小圓點),所以我設定了isMove作為一個變數,解決這個佇列問題,
就是當執行淡入淡出事件時,isMove變為false,當執行淡入淡出事
件完畢后,isMove再變為true,這樣當你點擊過快時,當次的淡入淡
出還沒完畢是不會執行下一次的淡入淡出事件的,
emmm…第一次寫博客感覺自己廢話多了點,嘿嘿,希望我的博客對
你們有點幫助,嘿嘿!拜拜下次見!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/298969.html
標籤:其他
上一篇:js簡單抽獎
