繁体   English   中英

如何使用 Javascript 随机更改背景颜色?

[英]How can I change the background color randomly with the Javascript?

我想在用户刷新页面后更改背景颜色

您可以通过jQuery完成,请检查以下代码:

$(document).ready(function() {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
    $("#background").css("background-color", '#' + randomColor);
});

 <html> <head> <script type="text/javascript"> function func() { //alert(getRandomColor()); document.body.style.backgroundColor = getRandomColor(); } function getRandomColor() { var letters = "0123456789ABCDEF".split(''); var color = "#"; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; } </script> </head> <body onload="func()"> </body> </html> 

您必须为在文档上运行的函数创建一个函数,如下所示:

<script type="text/javascript>
    $(document).ready(function() {
    var random_color = get_random_color();
        $("#background").css("background-color", random_color);
    });
    function get_random_color() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
</script>

JavaScript:

<div id="backgroundsection">
    <button id="buttonClick">Change color</button>
    <h4>HEX Color:<span class="texthex"></span></h4>
</div>

<style>
    #backgroundsection {
        display: flex;
        justify-content: center;
        align-items: center;
        color: #ffffff;
        background-color: #000000;
        height: 100px;
    }
</style>

<script>
    const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']; //array of all hex color values
    const textColor = document.querySelector(".texthex") //find an element for the subsequent replacement of the text in it with the current hex color
    const buttonClick = document.getElementById("buttonClick"); //color change button

    buttonClick.addEventListener("click", function () { //click event
       let colorhex = "#"; // a variable that will contain a hex color
        for(let i=0; i<6; i++) { //a loop that creates 6 values
            colorhex += hex[rundomnumber()];
        }
        textColor.textContent = colorhex; //substitute the current hex color value in span class="texthex"
        document.body.style.backgroundColor = colorhex; //change the body color
    });
    
    function rundomnumber() { 
        return Math.floor(Math.random() * hex. length); //a function that creates a random value from an array "hex"
    }


</script>

暂无
暂无

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

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