Native javascript+CSS realizes the effect of carousel map
- 2021-11-13 00:22:28
- OfStack
In this paper, we share the specific code of javascript+CSS to realize the carousel effect for your reference. The specific contents are as follows
1.html
<ul id="banner" ></ul>
2.css
ul{
list-style:none;
position: absolute;
padding: 0;
left: 0;
right: 0;
bottom: 0;
top:0;
margin:auto;
width: 800px;
height:200px;
}
3.js
// Generate carousel graph
export function generateBanner(){
let sz = new Array();
let cur_ul = document.getElementById('banner');
const recommends = this.recommends;
let timer = setInterval(getNextLi, 3000);
// Generate carousel graph li
for (let i = 0; i < recommends.length; i++) {
// Generate labels
let cur_li = document.createElement("li");
let cur_img = document.createElement("img");
// Append attribute
cur_img.src = recommends[i].pic;
// Append style
cur_li.style.position = 'absolute';
cur_li.style.left = '0px';
cur_li.style.transitionDuration = '0.4s';
cur_li.style.cursor="pointer";
//ul Total width 800 , showing 1 Zhang intact 400px Two incomplete ones 200px
cur_img.style.width = '125px';
cur_img.style.height = "100px";
// Append child elements
cur_li.appendChild(cur_img);
cur_ul.appendChild(cur_li);
// Put it all into the array for good operation
sz.push(cur_li);
}
// Generate two icons
generateAngleIcons();
// Will last 3 A picture is used to show
let len = sz.length - 1;
// Reciprocal 3 Zhang
showThreeLi();
// Get the following 1 A li Display, set the 1 Put them at the end of the array
function getNextLi() {
const li = sz[0];
sz = sz.slice(1);
sz.push(li);
// All li Restore
for (let i = 0; i < sz.length; i++) {
//li Restore all to original size
sz[i].style.transform = "scale(1)";
sz[i].style.left = "0px";
// From small to large li Covers accordingly
sz[i].style.zIndex = i;
// Hide All
sz[i].style.display = "none";
}
// Show the last 3 Zhang
showThreeLi();
}
// Show the last 3 Zhang
function showThreeLi() {
sz[len - 2].style.left = "0px";
// Reciprocal 2 Zhang
sz[len - 1].style.left = "120px";
sz[len - 1].style.zIndex = 100;
sz[len - 1].style.transform = "scale(1.3)";
// Reciprocal 1 Zhang
sz[len].style.left = "230px";
// Display
sz[len - 2].style.display = "block";
sz[len - 1].style.display = "block";
sz[len].style.display = "block";
}
function generateAngleIcons(){
const icons = new Array();
for (let i = 0; i < 2; i++) {
// Generate icons li
let cur_li = document.createElement("li");
// Append style
cur_li.style.position = 'absolute';
cur_li.style.top = '0px';
cur_li.style.bottom = '0px';
cur_li.style.margin = "auto";
cur_li.style.paddingTop="100px";
cur_li.style.paddingBottom="100px";
cur_li.style.zIndex = 20;
icons.push(cur_li);
}
icons[0].style.left = '0px';
icons[1].style.right = '0px';
icons[0].innerHTML = '<i class="angle left icon"></i>'
icons[1].innerHTML = '<i class="angle right icon"></i>'
cur_ul.appendChild(icons[1]);
cur_ul.appendChild(icons[0]);
}
}