简体   繁体   中英

Change background colour and text colour on click

What I have been trying -unsuccessfully- to achieve is to change the colour of the background and the text by clicking one <a> element, randomly rotating amongst several colour combinations.

My default colours are:

color: #1B1725;
background-color: #A30B37;

I would like to use, at least, three colour combinations more (for the sake of this example, those three other combinations can be basic colours).

You can generate random colors like this:

    var bg = Math.floor(Math.random()*16777215).toString(16);
    var text = Math.floor(Math.random()*16777215).toString(16);
    var div = document.getElementById('mydiv');
    var a= document.getElementById('atagid');
    a.onclick = function() {
      div.style.backgroundColor = "#"+bg;
      div.style.color= "#"+text;
    }

Here is sandbox example:https://codesandbox.io/s/currying-cherry-nt80k?file=/index.html

function getColorChange(){
    var x = 1
    var a = "black"

    var intervalID = setInterval(function () {
        document.getElementById("changeColor").style.backgroundColor = a;
        if (x == 1) {
            a = "green"
        }
        if (x == 2 ) {
            a="red"
        }
        if (++x === 4) {
            window.clearInterval(intervalID);
        }
    }, 5000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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