繁体   English   中英

来自数组 JavaScript 的随机颜色

[英]Random color from array JavaScript

我是 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 都是数组中的随机颜色

您的代码已经有效。 你只是搞砸了一些报价。 JS 的正确 HTML 如下所示:

<body onload="start()">
    <div id="sq"></div>
</body>

一种更高级的方法是在 JavaScript 本身的事件DOMContentLoaded上调用addEventListener这里有更多信息)。 在这种情况下,HTML 和 JS 被正确分离。

 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; }
 <div id="sq"></div>

这段代码是随机改变body的背景颜色

 //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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM