在做的Django项目首页想添加个图片轮播的效果,效果为:共3张图片,图片1s自动更换一次,图片右下角有数字跳转对应图片。
以下代码借鉴博客地址:https://blog.csdn.net/Zhangeq/article/details/84306332
根据自己的项目效果,略作修改。
实现步骤如下:
1.添加css文件,我命名为picShow.css
*{margin:0px;border: 0}
.broadcast{
margin-top: 20px;
margin-left: 20px;
width: 650px;
height: 420px;
position: relative;
overflow: hidden;
}
.broadcast ul{
width: 300%;
height: 100%;
left: 0;
top: 0;
padding: 0;
list-style: none;
}
.broadcast li{
left: 0;
float: left;
list-style: none;
}
.broadcast img{
width: 650px;
height: 420px;
}
.broadcast ol{
position: absolute;
right: 30px;
bottom: 30px;
}
.broadcast ol li{
position: relative;
float: left;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: rgba(155, 155, 155,.45);
color: #fff;
text-align: center;
margin-right: 15px;
cursor: pointer;
line-height: 20px;
}
.broadcast ol li.first-li{
background-color:rgba(248, 248, 248, 0.45)
2.添加js文件,我命名为picShow.js
window.onload = function () {
var broadcast = document.getElementById("broadcast"),
img_list = document.getElementById("img_list"),
button_list = document.getElementById("button_list").getElementsByTagName("li"),
index = 0,
timer = null;
//初始化
if (timer) {
clearInterval(timer);
timer = null;
}
// 自动切换
timer = setInterval(autoPlay, 1000);
// 调用自动播放函数
function autoPlay() {
index++;
if (index >= button_list.length) {
index = 0;
}
imgChange(index);
}
function imgChange(buttonIndex) {
for (let i = 0; i < button_list.length; i++) {
button_list[i].className="";
}
button_list[buttonIndex].className = "first-li";//按钮样式切换
img_list.style.marginLeft = -650 * buttonIndex + "px";
index = buttonIndex;
}
//鼠标接触div
broadcast.onmouseover = function(){
clearInterval(timer);
}
//鼠标离开div
broadcast.onmouseout = function(){
timer = setInterval(autoPlay, 2000);
}
//鼠标悬停ol
for (var i = 0; i < button_list.length; i++) {
button_list[i].id = i;
button_list[i].onmouseover = function() {
clearInterval(timer);
imgChange(this.id);
}
}
}
3.在html中添加代码:
(1)在html的< head >< /head>中添加如下代码,引用js和css文件:
<link rel="stylesheet" href="{% static 'appadmin/css/picShow.css' %}">
<script type="text/javascript" src="{% static 'appadmin/js/picShow.js' %}"></script>
ps:上面href和src因为我配置了静态文件地址,如果没配置,可以使用直接写存放文件路径的方式。
(2)在html的< body >< /body>中添加如下代码,加入图片控件:
<div class="broadcast" id="broadcast">
<ul id="img_list">
<li><img src="{% static 'appadmin/img/timg.jpg' %}" alt="1"></li>
<li><img src="{% static 'appadmin/img/timg (1).jpg' %}" alt="2"></li>
<li><img src="{% static 'appadmin/img/timg (2).jpg' %}"alt="3"></li>
</ul>
<ol id="button_list"> <!-- 轮播按钮 -->
<li class="first-li" id="olli1">1</li>
<li id="olli2">2</li>
<li id="olli3">3</li>
</ol>
</div>
4.如需要修改图片个数:
(1)修改css样式
(2)修改html内容
5.如需要修改图片大小:
(1)修改css样式
两者保持一致,也可根据个人效果实现不同去设置。
(2)修改js逻辑
如果有其他需求,可以看看代码去改,代码都很好理解的,有问题也可私信我,大家一起进步~~~
加油~~~~