2017-05-16 52 views
-3

這是JavaScript和HTML和CSS我很新的JavaScript問題是如果語句總是顯示錯誤,即使它不應該如果語句總是假的即使我點擊贏變量的顏色值,數組顏色的第三個指標值的顯示錯誤如果語句總是假的,即使條件在Java腳本中爲真

var colors = [ 
 
\t "rgb(255,0,0)", 
 
\t "rgb(255,255,0)", 
 
\t "rgb(0,255,0)", 
 
\t "rgb(0,255,255)", 
 
\t "rgb(0,0,255)", 
 
\t "rgb(255,0,255)" 
 
\t ] 
 
var win =colors[3]; 
 
var winclrdisplay=document.querySelector(".winclr"); 
 
var square= document.querySelectorAll(".square"); 
 

 
\t winclrdisplay.textContent=" "+ win; 
 
\t 
 
\t for (var i = 0 ;i < square.length ; i++){ 
 
\t \t //colors 
 
\t \t square[i].style.background =colors[i]; 
 
\t \t 
 
\t \t // click listener 
 
\t \t square[i].addEventListener("click", function(){ 
 
\t \t var click = this.style.background; 
 
\t \t if (click == win){ 
 
\t \t \t alert("correct"); 
 
\t \t }else{ 
 
\t \t \t alert("wrong"); 
 
\t \t } 
 
\t \t } 
 
    \t \t); 
 
\t }
body { 
 
\t background-color: #232323; 
 
} 
 

 
.square{ 
 
\t width: 30%; 
 
\t background: purple; 
 
\t padding-bottom: 30%; 
 
\t float: left; 
 
\t margin: 1.66%; 
 

 

 
} 
 

 
#container { 
 
\t max-width: 600px; 
 
\t margin: 0 auto; 
 
} 
 
h1 { 
 
\t color:white; 
 
}
<html> 
 
<head> 
 
\t <title>color guessing game</title> 
 
\t <link rel="stylesheet" type="text/css" href="colorapp.css"> 
 

 
</head> 
 
<body> 
 
\t <h1>The Great <span class="winclr"></span> colour Game</h1> 
 
\t 
 
<div id="container"> 
 
<div class="square"></div> 
 
<div class="square"></div> 
 
<div class="square"></div> 
 
<div class="square"></div> 
 
<div class="square"></div> 
 
<div class="square"></div> 
 
</div> 
 
<script type="text/javascript" src="colorapp.js"></script> 
 
</body> 
 
</html>

+1

你想要做一個'的console.log(點擊)',看看你是什麼樣的價值_actually_得到。 – CBroe

+3

可能的重複[如何比較jQuery/JavaScript中的兩個顏色值?](http://stackoverflow.com/questions/2377696/how-can-i-compare-two-color-values-in-jquery-javascript ) – CBroe

+0

考慮用十六進制代碼編寫顏色,可以將其作爲字符串進行比較 –

回答

0

這幾乎是不可能的理解你的問題,因爲它格式不正確。但是,從快看,你都缺少一個右)if statment

if (click == "rgb(0,255,255"){ 

應該

if (click == "rgb(0,255,255)"){ 

if (click == rgb(0,255,255)){ 

(再次,我不知道你是什麼瞄準)

+0

最後一個導致錯誤,因爲'rgb(...)'不會被定義.. – Founded1898

+0

我相信他只是想獲得他在頁面上點擊的rgb顏色。 – JORDANO

+0

是的,我想從頁面上點擊不同的方塊獲取顏色 –

1

use element.getComputedStyle。如果CSS樣式是內聯的,element.style將獲取該值。它總是虛假的,因爲它沒有價值。

像這樣

var element = document.getElementById('box'), 
      style = window.getComputedStyle(element), 
      bg = style.getPropertyValue('background-color'); 

    console.log(bg); 
+0

什麼是窗口元素colorapp.js:23 Uncaught TypeError:未能在'Window'上執行'getComputedStyle':參數1不是'Element'類型。在HTMLDivElement處爲 。 (colorapp.js:23) –

相關問題