2017-09-18 25 views
1

我怎样才能使这个工作与多种颜色?此外,我无法获取改变颜色的链接。换色器只适用于两种颜色

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>

+0

这是什么问题? –

+0

更多选择我认为你不能避免简化。您可以使用多个if/else if语句或一个更优雅的switch语句。 –

+0

当我点击A +并且背景变黑时,链接改变了颜色。你是什​​么意思更多的颜色?你会有更多的可点击的东西,将改变背景和链接到不同的颜色?如果是这样,只需复制你为A +所做的所有操作。你想让A +变成多种颜色吗?那怎么这样?随机?让用户决定? –

回答

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环节的工作。