【问题标题】:Switch CSS background colour on click using Javascript使用Javascript在点击时切换CSS背景颜色
【发布时间】:2015-08-04 20:10:41
【问题描述】:

我一直在使用此脚本在单击时切换 CSS 背景颜色,我正在尝试添加第三种颜色选项,但似乎无法使其正常工作。任何人都可以帮助使第三种颜色起作用吗?

这是我的 jsfiddle 链接:

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();
}

谢谢,

詹姆斯

【问题讨论】:

    标签: javascript java css colors background


    【解决方案1】:

    你可以使用取模运算符(%):

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

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

    【讨论】:

    • 也可以去掉函数Fiddlee.currentTarget.className = className[index++%className.length];
    【解决方案2】:

    试试这个 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();
    }
    

    【讨论】:

    • 这太完美了!是否可以在悬停时使上方的红色和点击时出现黑色?
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2017-12-28
      • 1970-01-01
      • 2015-10-03
      • 2014-08-07
      相关资源
      最近更新 更多