Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
大家好,我正在学习Web开发,并且我是完全的菜鸟。当我在块中输入鼠标时,它应该改变颜色,但似乎并没有改变颜色,我无法弄清楚为什么,可能是由于缺乏知识。

对不起,我的英语不好。

JS:



var squareGrid = function() {
  $('#gridContainer').html("");

  var input = prompt("Enter a number between 1 and 100.");
  var color = prompt("Enter a  Color i.e red,blue,black,yellow");
  var clr = color.toLowerCase();

  var squareSize = $('#gridContainer').width() / input - 2;

  for (var i = 1; i <= input; i++) {
    for (var j = 1; j <= input; j++) {
      $('#gridContainer').append('<div class="square"></div>');
    };
  }
  $('.square').css('width', squareSize);
  $('.square').css('height', squareSize);

  $('.square').mouseenter(function() {
    if (clr === black) {
      $(this).addClass('black');
    } else if (clr === red) {
      $(this).addClass('red');
    } else if (clr === blue) {
      $(this).addClass('blue');
    } else if (clr === yellow) {
      $(this).addClass('yellow');
    }
  });
}

CSS:

#buttonContainer {
  margin: auto;
  text-align: center;
}
button {
  width: 150px;
  height: 30px;
}
#gridContainer {
  overflow: auto;
  width: 960px;
  margin: auto;
}
.square {
  background-color: white;
  float: left;
  border: 1px solid black;
}
.black {
  background-color: black;
}
.red {
  background-color: red;
}
.blue {
  background-color: blue;
}
.yellow {
  background-color: yellow;
}
.new_row {
  clear: both;
}

HTML:

<!DOCTYPE html>
<html>

<head>
  <title>Sketch-Pad</title>
  <link rel="stylesheet" href="style.css" type="text/css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script src="script.js" type="text/javascript" charset="utf-8"></script>
  <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>

<body>
  <div id="buttonContainer">
    <button id="start" onclick="squareGrid()">Start!</button>
  </div>
  <div id="gridContainer"></div>

</body>

</html>

最佳答案

clr变量的值是一个字符串,因此在将其与一个值(即黑色)进行比较时,需要将该值用引号引起来。


$('.square').mouseenter(function() {
    if (clr === "black") {
      $(this).addClass('black');
    } else if (clr === "red") {
      $(this).addClass('red');
    } else if (clr === "blue") {
      $(this).addClass('blue');
    } else if (clr === "yellow") {
      $(this).addClass('yellow');
    }
  });

关于javascript - 草图板代码不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36361051/

10-12 13:34