来自数组JavaScript的随机颜色

时间:2015-05-04 14:52:07

标签: javascript html arrays

我是javascript的新手,所以提前抱歉这个问题的简单性。

在加载网页时,我希望我的div是我的数组中表示的随机颜色。

HTML

 body onload="start"()"

JS

var color = ["red", "blue", "yellow", "green"];

function start() {

    document.getElementById("sq").style.backgroundColor =     color[Math.floor(Math.random() * color.length)];
}

道歉,我无法将随机颜色设置为div。我试着直接设置颜色,即蓝色。那很有效。但是根本不使用数组。

所以最后,我希望每次启动网页时,我的div都是我的数组中的随机颜色

2 个答案:

答案 0 :(得分:4)

您的代码已经有效。你刚搞砸了一些引用。 JS的正确HTML看起来像这样:

IdHTTP1.CookieManager.AddServerCookie();

更优越的方法是在事件<body onload="start()"> <div id="sq"></div> </body> here are more informations)中使用JavaScript本身调用addEventListener。在这种情况下,HTML和JS被正确分开。

DOMContentLoaded
var color = ["red", "blue", "yellow", "green"];

// dom ready
document.addEventListener("DOMContentLoaded", function (event) {
    start()
});

function start() {
    document.getElementById("sq").style.backgroundColor = color[Math.floor(Math.random() * color.length)];
}
#sq {
    margin: 5px;
    border: 1px solid black;
    width: 50px;
    height: 50px;
}

答案 1 :(得分:1)

此代码是随机更改主体的背景颜色

//get the values form the html page in a const variables
const colorBtn = document.querySelector(".colorBtn");
const bodyBcg = document.querySelector("body");
const hex = document.querySelector(".hex");

//create an array of hex litearls
const hexNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];

//create an event listener linked button   
colorBtn.addEventListener("click", changeColor);

function changeColor() {
  //variables to stores hexvalue of the color
  let hexCol = "#";

  //Run for loop upto 6 times has hex value is of six literal long
  for (let i = 0; i < 6; i++) {
    //generates an random index less then 15
    let random = Math.floor(Math.random() * hexNumbers.length);
    //add all values to a variable
    hexCol += hexNumbers[random];
  }
  //change the color of the body background according to value we created
  bodyBcg.style.backgroundColor = hexCol;
  //shows the hex value which we get
  hex.innerHTML = hexCol;
}
body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.colorBtn {
  user-select: none;
  padding: 0.25rem 0.5rem;
  border: 1px solid #fefefe;
  border-radius: 7px;
  color: #fefefe;
  background-color: rgba(0, 0, 0, 0.6);
  font-size: 1.5rem;
  text-transform: capitalize;
  cursor: pointer;
  outline: none;
}

.colorBtn:hover {
  background-color: rgb(0, 0, 0);
}

.container {
  text-align: center;
}

.hexColor {
  text-transform: capitalize;
}

.hex {
  font-size: 3rem;
  display: block;
}
<div class="container">
  <h2 class="hexColor">This Color Code is : <span class="hex"></span></h2>
  <button type="button" class="colorBtn">
            Press Me To Change The Color
          </button>
  <script src="script.js"></script>
</div>