<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#banner {
width: 533px;
height: 300px;
outline: 10px solid #fff666;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="banner">
</div>
<script src="./demo.js"></script>
<script>
var bannerDiv = document.getElementById("banner");
createBannerArea(bannerDiv, [{
imgurl: "./imge/5d734abfdd0e92fa29f402056fc4560c.jpg"
},
{
imgurl: "./imge/5fee9229ca1f6274651495b51f1e8187.jpg"
},
{
imgurl: "./imge/aa988a78864d1f98ca563e5298ce7f93 (1).jpg"
}
])
</script>
</body>
</html>
function createBannerArea(areaDom, options) {
var imgArea = document.createElement('div');
var numberArea = document.createElement('div');
var curIndex = 0;
var changeTimer = null;
var changeDuration = 3000;
var timer = null;
initImge();
inittNumbers();
setStatus();
autoChange();
function initImge() {
imgArea.style.wdith = '100%';
imgArea.style.height = '100%';
imgArea.style.display = 'flex';
imgArea.style.overflow = 'hidden';
for (var i = 0; i < options.length; i++) {
var obj = options[i];
var img = document.createElement('img')
img.src = obj.imgurl;
img.style.wdith = '100%';
img.style.height = '100%';
img.style.marginLeft = '0';
img.style.cursor = 'pointer';
img.addEventListener('click', function () {
location.herf = options[i].link;
})
imgArea.appendChild(img);
}
imgArea.addEventListener('mouseenter', function () {
clearInterval(changeTimer);
changeTimer = null;
})
imgArea.addEventListener('mouseleave', function () {
autoChange();
})
areaDom.appendChild(imgArea);
}
function inittNumbers() {
numberArea.style.textAlign = 'center';
numberArea.style.marginTop = '-25px';
for (let i = 0; i < options.length; i++) {
var sp = document.createElement('span');
sp.style.width = '12px';
sp.style.height = '12px';
sp.style.background = 'lightgray';
sp.style.display = 'inline-block';
sp.style.margin = '0 7px';
sp.style.borderRadius = '50%';
sp.style.cursor = 'pointer';
sp.addEventListener('click', function () {
curIndex = i;
setStatus();
})
numberArea.appendChild(sp);
}
areaDom.appendChild(numberArea);
}
function setStatus() {
for (var i = 0; i < options.length; i++) {
if (i === curIndex) {
numberArea.children[i].style.background = '#be926f'
} else {
numberArea.children[i].style.background = 'lightgray'
}
}
var start = parseInt(imgArea.children[0].style.marginLeft);
var end = curIndex * -100;
var dis = end - start;
var duration = 500;
var speed = dis / duration;
if (timer) {
clearInterval(timer);
}
timer = setInterval(function () {
start += speed * 20;
imgArea.children[0].style.marginLeft = start + '%';
if (Math.abs(end - start) < 1) {
imgArea.children[0].style.marginLeft = end + '%';
clearInterval(timer);
}
}, 20);
}
function autoChange() {
if (changeTimer) {
return;
}
changeTimer = setInterval(function () {
if (curIndex === options.length - 1) {
curIndex = 0;
} else {
curIndex++;
}
setStatus();
}, changeDuration);
}
}