最近在看jquery東西,一時興起純手寫了一份jquery版的輪博圖,在此記錄一下。。。
實現效果如下:
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style> .content { position: relative;
} .carousel { position: relative; width: 800px; height: 350px; margin: 0 auto;
} .carousel>div:first-child { overflow: hidden; width: 800px; height: 350px;
} .carousel img { width: 800px; height: 350px;
} .item ul { display: flex; position: absolute; left: 50%; bottom: 0; transform: translateX(-50%) } .item ul li { list-style: none; width: 50px; height: 15px; background: rgba(0, 0, 0, 0.3); margin: 0 20px;
} .active { background: orangered !important;
} .left, .right { position: absolute; width: 30px; height: 60px; border: 1px solid #000; font-weight: 900; font-size: 22px; line-height: 60px; text-align: center;
} .left { left: -35px; top: 50%; transform: translateY(-50%);
} .right { right: -35px; top: 50%; transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="content">
<div class="carousel">
<div>
<img src="https://aecpm.alicdn.com/simba/img/TB1XotJXQfb_uJkSnhJSuvdDVXa.jpg" alt="">
<img src="https://aecpm.alicdn.com/simba/img/TB183NQapLM8KJjSZFBSutJHVXa.jpg" alt="">
<img src="https://img.alicdn.com/tfs/TB16AtDhzMZ7e4jSZFOXXX7epXa-520-280.jpg_q90_.webp" alt="">
<img src="https://img.alicdn.com/tfs/TB1PQ00TUH1gK0jSZSyXXXtlpXa-520-280.png_q90_.webp" alt="">
</div>
<div class="left"><</div>
<div class="right">></div>
</div>
<div class="item">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
<script src="./jquery-1.12.4.js"></script>
<script> let i = 0
function run() { // 獲取下標為 i 的圖片,讓下標為 i 的圖片顯示, 其他圖片隱藏
$('.carousel img').eq(i).show().siblings().hide() // 獲取輪播圖小標為 i 的小長方形按鈕,給 i 下標的按鈕添加類名active,刪除其他元素的類名active
$('.item ul li').eq(i).addClass('active').siblings().removeClass('active') } function times() {// 每2s執行一次run函數
return setInterval(() => { if (++i === 4) { i = 0 } run() }, 2000) } let timer = times() //調用
// 獲取輪播圖小按鈕,綁定鼠標事件
$('.item ul li').mouseenter(function () { clearInterval(timer) //清除計時器
i = $(this).index() // 獲取當前鼠標所在的按鈕下標
run() }) // 獲取輪播圖小按鈕,綁定鼠標離開事件,當鼠標離開后重新啟動定時器
$('.item ul li').mouseleave(function () { timer = times() }) // 左邊< , 點擊后圖片向左輪播
$('.left').click(function () { clearInterval(timer) if (--i < 0) { i = 3 } run() timer = times() }) // 右邊> ,點擊后圖片向右邊輪播
$('.right').click(function () { clearInterval(timer) if (++i === 4) { i = 0 } run() timer = times() }) </script>
</body>
</html>