简单编写样式,实现轮播图及导航条动画,代码如下:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link rel="stylesheet" href="./lunbo.css">
<style>
</style>
</head>
<body>
<div id="myCarousel" class="carousel slide" data-ride="carousel" data-pause="hover" data-interval="5000">
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox">
<div class="item active banner-one">
</div>
<div class="item banner-two">
</div>
<div class="item banner-three">
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
crossorigin="anonymous"></script>
<script>
</script>
</body>
</html>
CSS
.carousel-indicators {
bottom: -40px;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
}
#myCarousel {
width: 400px;
height: 400px;
margin: 0 auto;
}
.carousel-inner {
margin: 40px auto;
display: flex;
justify-content: center;
overflow: hidden;
}
.carousel-inner .item {
width: 400px;
height: 400px;
}
.banner-one {
background: pink;
}
.banner-two {
background: red;
}
.banner-three {
background: green;
}
.carousel-indicators li {
border: none;
background: #F0F4F8;
width: 60px;
height: 6px;
border-radius: 20px;
position: relative;
}
.carousel-indicators .active {
width: 60px;
height: 6px;
border-radius: 20px;
background: #F0F4F8;
}
.carousel-indicators .active::before {
content: "";
position: absolute;
background: linear-gradient(98.15deg, #0587f1 0%, #04eea0 99.24%);
left: 0;
height: inherit;
width: 0px;
animation: banner-active 5s linear;
animation-play-state: running;
border-radius: 20px;
}
.carousel:hover .carousel-indicators .active::before {
background: linear-gradient(98.15deg, #0587f1 0%, #04eea0 99.24%);
animation-play-state: paused;
animation-duration: 10000;
}
@keyframes banner-active {
from {
width: 0px;
}
to {
width: inherit;
}
}
ok,现在实现了hover暂停轮播和进度条,但移开鼠标轮播和进度条对不上了;
解决:鼠标移入时监听进度条动画事件,当动画结束时,进入下一张轮播图。
代码如下:
$('#myCarousel').mouseenter(function () {
$(".carousel-indicators .active")[0].addEventListener('animationend', function (e) {
if (e.pseudoElement === "::before") {
$('#myCarousel').carousel('next');
}
}, false);
})
$('#myCarousel').carousel({
interval: 5000,
pause: 'hover'
});
e.pseudoElement 获取伪元素