我一直試圖弄清楚最近幾個小時的這個編程任務,但是我陷入了一個部分。我目前有一個程序,onclick會隨機挑選一個元素並更改其背景顏色。如何修改程序,使其僅改變相鄰框的顏色(右)。因此,單擊將選擇該框,更改其顏色,然後下一次單擊將更改下一個框的顏色。請記住,這隻需要一段時間就可以完成。在JavaScript中更改下一個元素的顏色
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;
}
嗯,這是一個很好的回答太..釹那只是存放在變量值,所以沒有什麼壞在你的答案.. + 1 – 2015-03-05 04:39:25