在JavaScript中更改下一个元素的颜色

时间:2015-03-02 09:56:25

标签: javascript

我一直在努力弄清楚过去几个小时的编程工作,但我陷入了困境。我目前有一个程序,onclick会随机选择一个元素并改变它的背景颜色。如何修改程序,使其仅更改相邻框的颜色(右)。因此,单击将选中框,更改其颜色,然后下一次单击将更改下一个框的颜色。请记住,只需要一个while循环即可完成。

HTML:

<!DOCTYPE html>
<!--
     Your name does here
     The date goes here
     CISC 131

     A short description of the project goes here
-->
<html lang="en">
<head>
<title>this will appear on the tab in the browser</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="Changenxtonclick.js" type="text/javascript"></script>
<style type="text/css">
*{border: 0;
margin:0;
paddig: 0;
}
body{
font-family:"Times New Roman"; serif;
font-size: 12pt;
}
.box
{
    height: 10em;
    width: 10em;
    background-color: blue;
    float: left;
    margin: 1.5px;
}
</style>

</head>
<body>
<div class="box" id="box0"></div>
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
</body>
</html>

JS:

window.onload = function()
{
    document.onclick = changeBackgroundColor;
}
function changeBackgroundColor()
{
    var element;
    element = document.getElementById(generateId());
    element.style.backgroundColor = getRandomRGB();

}  // Changes the background color of the boxes.
function generateId()
{
    return "box" + getRandomInteger(3);

}
function getRandomRGB() // Uses getRandomInteger to generate random RGB colors.
{
    var red;
    var green;
    var blue;
    var result;
    red = getRandomInteger(255);
    green = getRandomInteger(255);
    blue = getRandomInteger(255);
    result = "rgb("+red+","+green+","+blue+")";
    return result;

}

function getRandomInteger(upperLimit) // Gets a random number on less than upperLimit
{
    var result;
    result = Math.random();
    result = result * (upperLimit + 1);
    result = Math.floor(result);




    return result;
}

2 个答案:

答案 0 :(得分:1)

看到这个小提琴:http://jsfiddle.net/e3zf64t6/

首次点击时选择一个随机元素并更改背景颜色,然后在下次点击时,它会更改下一个兄弟div的颜色

function changeBackgroundColor()
{

    if(clicked==0)
    {
    element = document.getElementById(generateId());
    clicked++;

    }else{
         element=element.nextSibling;
        console.log(element);
    }
    element.style.backgroundColor = getRandomRGB();

}

答案 1 :(得分:1)

您是否可以存储随机元素的ID?如果是这样,第一次点击将返回一个随机数,然后点击后可以增加数字。

e.g。

var selected = getRandomInteger(3); //Generate a random number
window.onload = function()
{
    document.onclick = changeBackgroundColor;
}
function changeBackgroundColor()
{
    var element;
    element = document.getElementById("box"+selected);
    element.style.backgroundColor = getRandomRGB();
    selected = ((selected+1)%4); //Increment the id using mod to loop around.
}

编辑: Naeem的答案更好,避免存储id:)