随机<divs> onclick

时间:2016-11-12 17:45:35

标签: javascript html css random

我正在尝试制作一个简单的游戏

  • 您从9个圈子开始

  • 当您点击带有较粗边框的圆圈时,它会增加分数并导致随机绘制新圆圈。

我已经在计算东西,但我有一个问题,因为无论你点击哪里(我的意思是无论什么div)它总结了点数。我不知道如何停用没有较粗边框的div。

请告诉我这是否是一种很好的编程方法。

photo of game

HTML

<body>
    <div class="container-fluid">
        <div class="row">
          <div class="col-md-2">
            <h1> Wyniki </h1> 
            <p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
          </div>

          <div class="col-md-8">
            <h1> Gra </h1>

            <div class="wynik">
                <h2> Rezultat </h2>
                <p id="zliczenie"> </p>
            </div>

            <div class="points"> </div>

          </div>

          <div class="col-md-2">
            <h1> Profil </h1> 
            <p> Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. </p>
          </div>
        </div>
    </div>
</body>

CSS

body {
background-color: #ecf0f1;
margin          : 2% 2%;
}

.wynik{
border          : solid 1px blue;
}

.point {
width           : 100px;
height          : 100px;
border          : solid 1px #000;
border-radius   : 100%;
text-align      : center;
cursor          : pointer;
float           : left;
margin          : 20px;
}
.point:hover {
color           : red;
border-radius   : 0%;
}

.points{
width           : calc(140px * 3);
margin          : 5px auto;
}

JS

window.onload = start;
function start()
{
        var div_value = "";

        for (i = 0; i < 9; i++) 
            {
                var element = "div_number" + i;
                div_value = div_value + '<div class="point" id="'+element+'" onclick="c('+i+')"> Klik </div>';

                if((i+1)%3 == 0) 
                {
                    div_value = div_value + '<div style="clear:both;"> </div>';
                } 

            }

        document.getElementsByClassName("points")[0].innerHTML = div_value; 

esthetic();
random_show();
}
// IT SHOWS 1 RANDOM DIV TO START THE GAME
function random_show() {
    var a = Math.floor((Math.random() * 8));
    var x = document.getElementById("div_number" + a).style.border="10px       dotted";
}

var liczby = [];
// IT DROWN LOTS AND COUNT THE SCORE
function c(i) 
{
    var a = Math.floor((Math.random() * 8));
    this.i = a;
    var z = document.getElementById("div_number" + i);
    var y = document.getElementById("div_number" + a);


    if(y.style.border = "10px dotted") {
        z.style.border ="5px dotted";
        liczby.push(i); 
    } else {
        y.style.border="8px solid";
    } 

    var x = document.getElementById("zliczenie").innerHTML = liczby.length;

}


// IT GIVES EVERY DIV INITIAL style.border 
function esthetic()
{
    var x = document.getElementsByClassName("point");
    for (i = 0; i < 9; i++) 
    {
        x[i].style.border = "5px dotted";

    }
}     

再次感谢任何提示!

4 个答案:

答案 0 :(得分:1)

您可以将当前有边界的div编号存储在变量中,每次调用click函数时,都可以检查相同的div编号是否触发了此函数调用。

以下是您修改后的代码:

window.onload = start;

function start() {
  var div_value = "";

  for (i = 0; i < 9; i++) {
    var element = "div_number" + i;
    div_value = div_value + '<div class="point" id="' + element + '" onclick="c(' + i + ')"> Klik </div>';

    if ((i + 1) % 3 == 0) {
      div_value = div_value + '<div style="clear:both;"> </div>';
    }

  }

  document.getElementsByClassName("points")[0].innerHTML = div_value;

  esthetic();
  random_show();
}

currDiv = 0;
// IT SHOWS 1 RANDOM DIV TO START THE GAME
function random_show() {
  var a = Math.floor((Math.random() * 8));
  currDiv = a; // assign current bordered div
  var x = document.getElementById("div_number" + a).style.border = "10px       dotted";
}

var liczby = [];
// IT DROWN LOTS AND COUNT THE SCORE
function c(i) {

  if (parseInt(i) == currDiv) { // check if the current div clicked is the bordered div

    var a = Math.floor((Math.random() * 8));
    this.i = a;
    var z = document.getElementById("div_number" + i);
    var y = document.getElementById("div_number" + a);

    currDiv = a; // change it to the current bordered div


    if (y.style.border = "10px dotted") {
      z.style.border = "5px dotted";
      liczby.push(i);
    } else {
      y.style.border = "8px solid";
    }

    var x = document.getElementById("zliczenie").innerHTML = liczby.length;

  }


}


// IT GIVES EVERY DIV INITIAL style.border 
function esthetic() {
  var x = document.getElementsByClassName("point");
  for (i = 0; i < 9; i++) {
    x[i].style.border = "5px dotted";

  }
}
body {
  background-color: #ecf0f1;
  margin: 2% 2%;
}
.wynik {
  border: solid 1px blue;
}
.point {
  width: 100px;
  height: 100px;
  border: solid 1px #000;
  border-radius: 100%;
  text-align: center;
  cursor: pointer;
  float: left;
  margin: 20px;
}
.point:hover {
  color: red;
  border-radius: 0%;
}
.points {
  width: calc(140px * 3);
  margin: 5px auto;
}
<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-2">
        <h1> Wyniki </h1> 
        <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.</p>
      </div>

      <div class="col-md-8">
        <h1> Gra </h1>

        <div class="wynik">
          <h2> Rezultat </h2>
          <p id="zliczenie"></p>
        </div>

        <div class="points"></div>

      </div>

      <div class="col-md-2">
        <h1> Profil </h1> 
        <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet.</p>
      </div>
    </div>
  </div>
</body>

希望它有所帮助!

答案 1 :(得分:1)

将样式保存在.html文件中的.css文件和html标记以及.js文件中的代码中始终是一种好习惯。

另外,为了检查元素上是否存在特定样式,您应该检查该元素在其类列表中是否具有特定类。请参阅:https://developer.mozilla.org/en/docs/Web/API/Element/classList

在.css中创建新类:

.boldCircle {
    border: 10px dotted;
}

在你的代码中只需:

if(y.classlist.contains("boldCircle")) {
    // Do what you want
}

我想指出的另一件事是if条件中的平等。你应该使用&#39; ==&#39;而不是&#39; =&#39;。 &#39; =&#39;是赋值运算符,并始终计算为true。

if (y.style.border == "10px dotted") {
    // Do what you want
}

答案 2 :(得分:1)

在@DeepakKumar建议的基础上,我还会考虑使用一个类将元素标记为活动目标。然后,您的点击事件处理程序可以检查它并根据需要增加点/管理您的数组。

我还简化了一些代码,以便为这个沙箱更好地格式化它。

&#13;
&#13;
// =====================
// Initialize the game
// =====================
function start() {
  var divTemplate = '<div id="%1%" class="point" data-index="%2%" onclick="c(event)"> Klik </div>';
  var clearTemplate = '<div style="clear:both;"> </div>';
  var elPoints = document.getElementsByClassName("points")[0];

  var div_value = "";

  for (i = 0; i < 9; i++) {
    div_value += divTemplate
                    .replace("%1%", "div_number" + i)
                    .replace("%2%", i);

    if ((i + 1) % 3 == 0) { div_value += clearTemplate; }
  }

  elPoints.innerHTML = div_value;

  liczby = [];
  random_show();
}
// =====================

// =====================
// Set one div as the target
// =====================
function random_show() {
  var a = Math.floor((Math.random() * 8));
  var elCurrentTarget = document.querySelector(".point.target");
  var elNewTarget = document.getElementById("div_number" + a);

  if (elCurrentTarget) { elCurrentTarget.classList.remove("target"); }
  elNewTarget.classList.add("target");
}
// =====================

// =====================
// If the target div was clicked increment the score
// reset the board.
// =====================
function c(event) {
  var elTarget = event.target;
  var elScore = document.getElementById("zliczenie");

  if (elTarget.classList.contains("target")) {
    liczby.push(elTarget.getAttribute("data-index"));
    elScore.innerHTML = liczby.length;
  }

  random_show();
}
// =====================

var liczby = [];
window.onload = start;
&#13;
.wynik {
  border: solid 1px blue;
}

.points {
  width: calc(140px * 3);
  margin: 5px auto;
}

.point {
  width: 60px;
  height: 60px;
  border: solid 1px #000;
  border-radius: 100%;
  text-align: center;
  cursor: pointer;
  float: left;
  margin: 10px;

  border: 5px dotted;
}

.point.target {
  border: 10px dotted;
}

.point:hover {
  color: red;
  border-radius: 0%;
}
&#13;
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha256-916EbMg70RQy9LHiGkXzG8hSg9EdNy97GazNG/aiY1w=" crossorigin="anonymous" />

<div class="container-fluid">
  <div class="row">
    <div class="wynik">
      <span>Rezultat: </span><span id="zliczenie"></span>
    </div>
    <div class="points"></div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=" crossorigin="anonymous"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:1)

以下代码表示&#34;如果您点击粗圆,则得分+ 1,得分 - 否则为&#34; :

score += i == winning ? +1 : -1;

有关详细信息,请参阅conditional operator

关于随机性的帖子:https://stackoverflow.com/a/32395535/1636522

&#13;
&#13;
var boardEl = document.getElementById("board"), 
    scoreEl = document.getElementById("score"), 
    indexOf = Array.prototype.indexOf, 
    winning = 0, 
    score = 0;

scoreEl.textContent = "( " + score + " )";
boardEl.innerHTML = new Array(10).join("<a href=\"#\"></a>");
boardEl.childNodes[winning].setAttribute("class", "winning");

boardEl.onclick = function (ev) {
  var i, rdm, winningEl;
  ev.preventDefault();
  if (ev.target.parentNode == boardEl) {
    i = indexOf.call(boardEl.childNodes, ev.target);
    score += i == winning ? +1 : -1;
    winningEl = boardEl.childNodes[winning];
    winningEl.setAttribute("class", "");
    rdm = Math.floor(Math.random() * 8);
    winning = rdm >= winning ? rdm + 1 : rdm;
    winningEl = boardEl.childNodes[winning];
    winningEl.setAttribute("class", "winning");
    scoreEl.textContent = "( " + score + " )";
  }
};
&#13;
#board, #score {
  display: inline-block;
  vertical-align: middle;
}

#board {
  width: 150px;
}

#score {
  font: bold 32px Arial;
  color: #666;
}

#board a {
  vertical-align: top;
  display: inline-block;
  border: 5px dashed #666;
  border-radius: 50%;
  height: 30px;
  width: 30px;
  margin: 5px;
}

#board a.winning {
  border-width: 10px;
  height: 20px;
  width: 20px;
}

#board a:hover {
  border-color: black;
}
&#13;
<div id="board"></div>
<div id="score"></div>
&#13;
&#13;
&#13;