简体   繁体   English

在一个小方形 div 中添加数字

[英]Add number in a small square div

this is a codepen demo at here and you try to click on the canvas and is able to undo and clear the grid.这是此处的代码笔演示,您尝试单击 canvas 并能够撤消和清除网格。 The problem I am trying to solve is I want to place some numbers (in black) in the red square.我要解决的问题是我想在红色方块中放置一些数字(黑色)。 For example, when you click on the grid, first red dot will appear and inside labelled as 1 and the second will be labelled 2 and so on and if the dots overlap, it will just show the original number(not a new number).例如,当您单击网格时,将出现第一个红点并在内部标记为 1,第二个将标记为 2 等等,如果这些点重叠,它将只显示原始数字(不是新数字)。 I have tried to use the code below:我尝试使用以下代码:

var elements = document.getElementsByClassName('red-dot');    
  elements.innerHTML = 'Testing here';

Thank you for reading:)感谢您的阅读:)

This should do it:这应该这样做:

  • accessing elements by classname needs to be by index eg document.getElementsByClassName(.red-dot)[0] will access the first element with the classname red-dot按类名访问元素需要按索引,例如document.getElementsByClassName(.red-dot)[0]将访问具有类名红点的第一个元素
  • in the codepen you used style top and left to position the red-dot, so i used it as skip if taken by an element of the same class name在 codepen 中,你使用样式顶部和左侧到 position 红点,所以如果被具有相同 class 名称的元素采用,我将它用作跳过

The rest is self explanatory. rest 是不言自明的。

var elements = document.getElementsByClassName('red-dot');
    var eLength = elements.length;
    const dValue = parseInt(eLength) + 1;
    let isTaken = false;
    
    // check if dot number is taken
    for (let d=0;d<eLength;d++) {
      let top = elements[d].style.top;
      let left = elements[d].style.left;
      if (top == newDot.style.top && left == newDot.style.left) {
        isTaken = true;
      }
    }
    if (!isTaken) {
      newDot.dataset['dvalue'] = dValue;
      newDot.innerHTML = newDot.dataset.dvalue;
    } else {
      newDot.style.backgroundColor = 'transparent';
    }
    
    document.body.appendChild(newDot);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM