简体   繁体   中英

Switch CSS background colour on click using Javascript

I have been using this script to switch CSS background colour on click and I am trying to add a third colour option but can't seem to get it working. Can anyone help to get the third colour to work?

Here is my jsfiddle link:

https://jsfiddle.net/pkrWV/70/

var bodyObj, className, index;

bodyObj = document.getElementById('body');
index = 1;
className = [
    'imageOne',
    'imageTwo',
     'imageThree',
];

function updateIndex(){
    if(index === 0){
        index = 1;
    }else{
        index = 0;
    }
}

bodyObj.onclick = function(e){
    e.currentTarget.className = className[index];
    updateIndex();
}

Thanks,

James

You can use modulus operator (%):

function updateIndex(){
    index = (index+1)%(className.length);   
}

JSFiddle: https://jsfiddle.net/pkrWV/71/

https://jsfiddle.net/pkrWV/72/

function updateIndex(){
    if(index === className.length-1){
        index = 0;
    }else{
        index = index+1;
    }
}

Try this jsfiddle:

three colors

var bodyObj, className, index;

bodyObj = document.getElementById('body');
index = 1;
className = [
    'imageOne',
    'imageTwo',
     'imageThree',
];

function updateIndex(){
    index++;
    if (index===3) {
        index = 0;
    }
}

bodyObj.onclick = function(e){
    e.currentTarget.className = className[index];
    updateIndex();
}

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