批改状态:未批改
老师批语:
用jQurey改写轮播图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<style>
.box {
width:1920px;
height: 500px;
}
.box ul {
padding: 0;
margin: 0;
}
/*将全部图片样式默认不显示*/
.box ul:first-of-type li {
display: none;
list-style: none;
}
.box ul:last-of-type {
text-align: center;
margin-top: -50px;
}
.box ul:last-of-type li {
list-style: none;
display: inline-block;
width: 30px;
height: 30px;
line-height: 30px;
background-color: black;
color: white;
border-radius: 50%;
margin: 0 5px;
}
.box ul:last-of-type li:hover {
cursor: pointer;
background-color: white;
color: black;
}
</style>
</head>
<body>
<div class="box">
<!-- 轮播图片-->
<ul class="slider">
<!-- jQuery中的遍历数组从0开始显示,所以将图片名字改成0,1, 2-->
<li id="active" style="display: block"><img src="static/images/banner0.jpg" alt=""></li>
<li><img src="static/images/banner1.jpg" alt=""></li>
<li><img src="static/images/banner2.jpg" alt=""></li>
</ul>
<!-- 切换按钮-->
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<script src="static/js/jquery-3.4.1.js"></script>
<script>
//原生JavaScript代码
// 获取到所有按钮
// var lis = document.querySelectorAll('.box ul:last-of-type li');
// // 获取当前正在显示的图片
// var currentImg = document.querySelector('#active img');
//
// // 点击后切换图片
// for (var i = 0; i < lis.length; i++) {
// // 自定义索引,获取到当前正在显示的图片索引
// lis[i].index = i;
// // 给每一个按钮添加点击事件
// lis[i].onclick = function () {
// currentImg.src = 'static/images/banner'+parseInt(this.index+1) + '.jpg';
// };
// }
//
// // 用间歇式定时器, 每隔2秒随机切换图片
// setInterval(function () {
// var n = Math.floor(Math.random()*3)+1;
// currentImg.src = 'static/images/banner'+parseInt(n) + '.jpg';
// }, 2000);
//jQuery改写
var lis =$('.box ul:last-of-type li'); //获取所有的按钮
var currentImg = $('#active img')[0];//获取焦点图片
// //测试
console.log(lis);
console.log(currentImg);
//用$.each()遍历数据,直接在函数内添加点击函数
$.each(lis,function (value,element) {
$(element).on('click',function(){
console.log(value);
currentImg.src='static/images/banner'+ value + '.jpg';
console.log(currentImg.text);
$(element).css('background-color','#42426F');//选中显示
//移除当前显示图片函数
remove();
})
});
//移出添加的图片函数
function remove(){
for(var i = 0; i<lis.length; i ++){
$(lis[i]).attr('style','');
}
}
setInterval(function () {
//添加一个1至3的随机数
var n = Math.floor(Math.random()*3);
currentImg.src = 'static/images/banner'+ parseInt(n) + '.jpg'; //用parseInt获取整数输出
for(var i = 0; i<lis.length; i ++) {
$(lis[i]).attr('style', '');
}
$(lis[n]).css('background-color','#42426F');
// $(lis[n]).css('color','black');
}, 2000);
</script>
</body>
</html>点击 "运行实例" 按钮查看在线实例
因为遍历数组是从0开始,所以将原有图片名字改成0,1,2,三张
实际显示效果(截取了其中一张图片显示):

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号