我正在尝试使用第二个html按钮使数组向后移动但由于某种原因我不能,此代码使Div更改颜色甚至是您想要的颜色。现在我的疑问是如何让它循环或减少一些如何?
<head>
<title></title>
<style>#placeDiv{width:100px;height:100px;}</style>
</head>
<body>
<div id = "placeDiv">ok</div>
<button onclick="forward()">Forward</button>
<script>
var myArray = ["black","yellow","black","red","blue"];
var i = 0;
function forward(){
if(myArray.length <= i) i=0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i++];
};
</script>
</body>
答案 0 :(得分:2)
我已经使用jsfiddle链接添加了您所询问事物的完整正确实现。
HTML
<div id = "placeDiv">ok</div>
<button onclick="forward()">Forward</button>
<button onclick="backward()">Backward</button>
JS
var myArray = ["black","yellow","green","red","blue"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
forward=function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){
if(i == 0)
{i=myArray.length-1;}
else
{
i=i-1;
}
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
}
JSFiddle链接,其中我有演示
答案 1 :(得分:1)
你可以试试这个:
var myArray = ["black","yellow","black","red","blue"];
var i = 0;
function forward(){
if (myArray.length == i) i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i++];
};
function backward(){
if (i == -1) i = myArray.length - 1;
document.getElementById("placeDiv").style.backgroundColor = myArray[i--];
};