前言
刚学js没多久,这篇博客就当做记录了,以后还会完善的,希望大佬们多多指点。ps:下面出现的都是直接闪动,没有滑动效果的轮播图。
单张图片的替换
原理
1.将几张图片叠在一起,通过改变"display:block"和"display:none"这两个属性实现替换。 (前提:在css中给所有图片加上display:none属性)
2.不用将图片叠在一起,将一个div当做"窗口",通过"offset(height/top/width/left)"属性获取图片的
(高/到顶部距离/宽/到左边距离/到右边距离),再通过事件更改相应的属性,让图片在"窗口"内整体移动。
样例一
//
window.onload = function () {//页面加载时启用函数
Carouselfigure();//函数名可任意
};
function Carouselfigure() {
var next = document.getElementsByClassName("right")[0];//点击切换下一张的按钮
var prev = document.getElementsByClassName("left")[0];//点击切换上一张的按钮
var img = document
.getElementsByClassName("innerbox")[0]
.getElementsByTagName("img");//获取图片数组
var index = 0;//定义一个函数做工具人,“index”可改为任意名称
img[0].style.display = "block";//使页面加载后第一张图片显示
next.onclick = function () {//绑定切换下一张图片的点击事件
img[index].style.display = "none";//隐藏当前图片
if ((index == 3)) {//if语句使其循环
index = 0;
} else {
index++;//通过index的切换实现图片的切换
}
img[index].style.display = "block";//显示图片
};
prev.onclick = function () {//绑定切换上一张图片的点击事件
img[index].style.display = "none";//隐藏当前图片
if ((index == 0)) {//if语句使其循环
index = 3;
} else {
index--;//通过index的切换实现图片的切换
}
img[index].style.display = "block";//显示图片
};
}
样例二
//html
<body>
<div class="button">
<div class="left"></div>
<div class="right"></div>
</div>
<div class="allbox">
<div class="outbox">
<div class="innerbox">//用来移动的div
<img src="1.jpg">
<img src="2.jpg">
<img src="3.jpg">
<img src="4.jpg">
</div>
</div>
</div>
</body>
//css
*{
margin: 0;
padding: 0;
}
.allbox{
display: flex;
justify-content: center;
width: 100%;
margin-top: 50px;
height: 300px;
}
.outbox {
position: relative;
height: 300px;
width: 25%;
overflow: hidden;//使溢出div的图片隐藏
}
.innerbox {
position: absolute;
display: flex;//让图片横向排列
width:100%;
}
.innerbox img {
width: 100%;
height: 300px;
}
.button{
position: relative;
display: flex;
justify-content: center;
}
.left{
width: 50px;
height: 50px;
background-color:red ;
cursor: pointer;
}
.right{
width: 50px;
height: 50px;
background-color: black;
cursor: pointer;
}
//js
window.onload = function () {
Carouselfigure();
};
function Carouselfigure() {
var next = document.getElementsByClassName("right")[0];
var prev = document.getElementsByClassName("left")[0];
var innerbox = document.getElementsByClassName("innerbox")[0];
var img = document
.getElementsByClassName("innerbox")[0]
.getElementsByTagName("img");
var index = 0;
function move() {//设置该函数为移动函数
innerbox.style.left = -img[0].offsetWidth * index + 'px';
//offsetWidth用来获取图片的宽度,由于这几张图片的宽度相同,取任意一张的宽度都可,故选用数组中的0.负号是因为改变的是left的值,为了按图片顺序从左到右,才使用负号(可自行更换)。
}
next.onclick = function () {
if (index == 3) {
index = 0;
}
else { index++; }
move();//运行移动函数来实现效果
}
prev.onclick = function () {
if (index == 0) {
index = 3;
}
else { index--; }
move();//运行移动函数来实现效果
}
}
多张图片的替换(一次动一张)
多张图片的替换其实和单张图片的原理二是一样的,只不过要稍稍做一点变化。↓