相信我们的工作之中,制作轮播图是必不可少的,这也是前端最为基础的一个部分,制作轮播图的办法有很多,今天我就分享一下自己用原Q框架做出的轮播图。
ps:具体的思路我也会写在注释中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>轮播图</title>
<style>
#banner {
user-select: none;
width: 600px;
height: 300px;
background-color: aquamarine;
position: relative;
overflow: hidden;
}
#banner > div:last-child {
display: flex;
position: absolute;
bottom: 10px;
right: 10px;
}
#banner > div:last-child > img {
width: 40px;
height: 40px;
border-radius: 4px;
border: 2px solid white;
margin-left: 3px;
}
#banner > div:last-child > img.cur {
border-color: orange;
}
#banner > div:first-child {
display: flex;
}
#banner > div:first-child > img {
/* 弹性盒子中的元素: 默认自动拉伸, 导致宽高无效 */
/* flex:none; 关闭宽高自动拉伸 */
flex: none;
width: 100%;
display: inline-block;
height: 300px;
}
/* 图片挨着摆放的, 只要把第一张图向左移动, 其他图片会联动 */
/* #banner > div:first-child > img:first-child {
margin-left: 300px;
} */
</style>
</head>
<body>
<div id="banner">
<div>
<img src="./images/1-l.jpg" alt="" />
<img src="./images/2-l.jpg" alt="" />
<img src="./images/3-l.jpg" alt="" />
<img src="./images/4-l.jpg" alt="" />
</div>
<div>
<img class="cur" src="./images/1.jpg" alt="" />
<img src="./images/2.jpg" alt="" />
<img src="./images/3.jpg" alt="" />
<img src="./images/4.jpg" alt="" />
</div>
</div>
<script src="./jquery-3.6.0.js"></script>
<script>
$('#banner>div:last-child').on('mouseover', 'img', function () {
$(this).addClass('cur').siblings().removeClass('cur')
// 获取当前悬浮图片 在小图中的序号, 进而算出大图的偏移量
const index = $('#banner>div:last-child>img').index(this)
// 动画方式, 移动 第一张大图的 左边距
const $bigImg = $('#banner>div:first-child>img:first-child')
// 停止所有动画队列, 开始当前次动画
$bigImg.stop(true).animate({
marginLeft: index * -600 + 'px',
})
})
// 定时: 3秒中自动切换到下一张
setInterval(() => {
// 找出当前项, 触发其下一个元素的 鼠标悬浮事件
// mouseover(): 没有参数, 代表触发事件
let $next = $('#banner .cur').next()
// 如果当前就是最后一个, 则 next 不存在
// 则滚动到 小图中的 序号0的
if ($next.length == 0) $next = $('#banner div:last-child>img:eq(0)')
$next.mouseover()
// console.log($('#banner .cur').next())
}, 3000)
</script>
</body>
</html>