目录
🍁定时器
🌺核心
🌺整体代码
🍂CSS
定时器
例如:http://t.csdnimg.cn/bmyf0 这篇博文中自定义动画中的点赞案例。
我们给加一个定时器,达到一个自动点赞的效果。
setTimeout
在执行过一次后就不再执行了
setInterval
轮播图效果
效果示例:
核心
$("li").eq(count).show().siblings().hide()
主要通过上面的代码逻辑,来使得我们对用的图片展示,其他图片隐藏。
而所有的图片我们可以通过ui,li的方式列举出来,然后将其隐藏,默认展示一张开始图片,然后通过定时器定时切换每张图片的展示和隐藏( show() and hide() ),也可以通过点击两边的滚动按钮进行图片的切换,或者下方的圆点,我们鼠标移动到第n个圆点,展示对应的第n张图片即可。
图片的切换
不管是定时器切换,还是点击按钮切换,我们都会使用到对应的下标,所以将对下表的判断设置为方法更加方便使用。
整体代码
HTML和JS
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery-3.5.1.min.js"></script>
<link rel="stylesheet" href="css/轮播图.css" />
</head>
<body>
<div class="cent">
<ul>
<li class="default"><img src="img/商品1.png" /></li>
<li><img src="img/商品2.png" /></li>
<li><img src="img/商品3.png" /></li>
<li><img src="img/商品4.png" /></li>
</ul>
<div class="acc">
<button class="leftButton"><</button>
<button class="rightButton">></button>
</div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
</div>
<script>
var count = 0;
//右滚动方法
function rightScroll() {
if (count >= $("li").length - 1) {
count = 0;
} else {
count++;
}
}
//左滚动方法
function leftScroll() {
if (count <= 0) {
count = $("li").length - 1;
} else {
count--;
}
}
//定时器(默认右滚动)
setInterval(function() {
rightScroll(count);
$("li").eq(count).show().siblings().hide();
}, 1500)
//圆点悬浮事件
$(".circle").mouseover(function(){
$(this).css("background-color","red");
//index()匹配的是当前所有同级元素的下标
count = $(this).index()-2;
console.log(count);
$("li").eq(count).show().siblings().hide();
})
$(".circle").mouseout(function(){
$(this).css("background-color","white");
})
//左右按钮点击事件
$(".leftButton").click(function() {
leftScroll();
$("li").eq(count).show().siblings().hide();
})
$(".rightButton").click(function() {
rightScroll();
$("li").eq(count).show().siblings().hide();
})
</script>
</body>
</html>
CSS
.cent{
width: 100%;
height: 300px;
text-align: center;
position: relative;
}
ul>li{
list-style: none;
display: none;
}
.default{
display: block;
}
ul>li>img{
width: 200px;
height: 200px;
}
/* 左右按钮 */
.acc{
position: relative;
}
.cent button{
height: 30px;
background-color: gray;
color: black;
font-weight: bold;
opacity: 0.4;
border: none;
}
.cent .leftButton{
position: absolute;
top: -132px;
left: 350px;
}
.cent .rightButton{
position: absolute;
top: -132px;
right: 310px;
}
/* 圆点 */
.cent .circle{
width: 6px;
height: 6px;
background-color: white;
border-radius: 6px;
float: left;
margin: 3px;
position: relative;
left: 360px;
top: -42px;
}