数组轮回 简洁写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>数组循环简洁写法</title>
<style>
.content {
margin: 100px auto;
width: 200px;
height: 200px;
}
.toolbar {
text-align: center;
}
.toolbar {
margin-left: 10px;
}
</style>
</head>
<body>
<div class="content"></div>
<div class="toolbar">
<button onclick="changeColor('prev');">prev</button>
<button onclick="changeColor('next')">next</button>
</div>
<script>
let colorList = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'];
let currentIndex = 0;
var content = document.getElementsByClassName('content')[0];
content.style.backgroundColor= colorList[currentIndex];
function changeColor (value){
let newIndex;
let length = colorList.length;
if (value === "prev") {
newIndex = (currentIndex - 1 + length) % length;
} else if (value === "next"){
newIndex = (currentIndex + 1) % length;
}
content.style.backgroundColor= colorList[newIndex];
currentIndex = newIndex;
}
</script>
</body>
</html>html