换色器仅适用于两种颜色

时间:2017-09-18 16:39:56

标签: javascript html

我如何使用多种颜色来完成这项工作?此外,我无法获得更改颜色的链接。



var div = document.getElementById('ColorChanger');
div.addEventListener('click', function(e){
    var self = this,
        old_bg = this.style.background;
    
    document.body.style.background = document.body.style.background=='black'? 'white':'black';
    document.body.style.color = document.body.style.color=='lime'? 'black':'lime';
    document.alinkColor = document.linkcolor=='red'? 'black':'red';
   
})

<div id="ColorChanger">A+</div>

<a href="#">
Test
</a>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以将所有颜色存储在这样的数组中:

var div = document.getElementById('ColorChanger');
var allColors = [];
var currentColor = 0;
allColors.push({bg:"red",front:"green"});
allColors.push({bg:"green",front:"yellow"});
allColors.push({bg:"purple",front:"white"});

div.addEventListener('click', function(e){
    var self = this,
        old_bg = this.style.background;

    document.body.style.background = allColors[currentColor].bg;
    document.body.style.color = allColors[currentColor].front;
   currentColor++;
if(currentColor == allColors.length) currentColor = 0;
})

要使用链接,你应该使用preventDefault。