2017-09-18 26 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環節的工作。