单击单个单元格并使用Javascript将颜色添加到HTML表格 [英] Clicking individual Cells and adding color to HTML table using Javascript

查看:53
本文介绍了单击单个单元格并使用Javascript将颜色添加到HTML表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个HTML表格(用户输入了cols和rows),并且还有一种动态的颜色选择方式。

I have created a HTML table (with user inputted cols and rows) and also have a dynamic way of selecting color.

现在我希望能够点击表格中的单个单元格并使用所选颜色为它们着色。到目前为止我有这个代码。

Now I want to be able to click on individual cells in the table and color them with chosen color. I have this code so far.

我的最终目标是能够在我再次点击提交时重置颜色。流量为:

My final goal is to be able to reset the colors when I hit "submit" again. Flow would be:


  1. 选择表格大小

  2. 选择颜色

  3. 为表格中的单元格着色

  4. 再次点击提交时重置表格

  1. Choose table size
  2. Choose color
  3. Color the cells in the table
  4. Reset the table upon hitting "submit" again

function makeGrid(ev) {
  ev.preventDefault();
  var heights = document.getElementById("inputHeight").value;
  var widths = document.getElementById("inputWidth").value;
  var body = document.getElementById("pixelCanvas");
  var table = document.createElement('TABLE')
  var tblB = document.createElement('TBODY');
  table.appendChild(tblB);
  for (var i=0; i<heights; i++){
    var tr = document.createElement('TR');
    table.appendChild(tr);
    for (var j=0; j<widths; j++){
      var td = document.createElement('TD')
      document.getElementById("pixelCanvas").onclick = function(){
        td = document.getElementById("colorPicker").value;
        alert(td);
      }
      table.appendChild(td);
    }
  }
  body.append(table);
  body.addEventListener('click', function(){
    var coloor = document.getElementById("colorPicker").value;
    body.style.backgroundColor = coloor;
  })
}

body {
    text-align: center;
}

h1 {
    font-family: Monoton;
    font-size: 70px;
    margin: 0.2em;
}

h2 {
    margin: 1em 0 0.25em;
}

h2:first-of-type {
    margin-top: 0.5em;
}

table,
tr,
td {
    border: 1px solid black;
    padding: 25px;
}

table {
    border-collapse: collapse;
    margin: 0 auto;
}

input[type=number] {
    width: 6em;
}

<!DOCTYPE html>
<html>
<head>
    <title>Pixel Art Maker!</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <h1>Pixel Art Maker</h1>

    <h2>Choose Grid Size</h2>
    <form id="sizePicker" onsubmit="makeGrid(event)">
        Grid Height:
        <input type="number" id="inputHeight" name="height" min="1" value="1">
        Grid Width:
        <input type="number" id="inputWidth" name="width" min="1" value="1">
        <input type="submit" value= "submit">
    </form>

    <h2>Pick A Color</h2>
    <input type="color" id="colorPicker">

    <h2>Design Canvas</h2>
    <table id="pixelCanvas"></table>

    <script src="designs.js"></script>
</body>
</html>

推荐答案

编辑



添加了重置过程。还使用事件侦听器替换窗体上的内联属性事件(onsubmit)。

Edit

Added the reset process. Also replaced the inline attribute event (onsubmit) on the form with an event listener.



不要浪费资源将事件侦听器分配给吨< td> s ,请使用 活动委派 使用< table> 来收听所有< td> 而不是。有关实现模式的详细信息在演示中进行了评论,并且使用了更专业,更简洁,更高效的替代方法。


Don't waste resources on assigning event listeners to a ton of <td>s, use Event Delegation to use the <table> to listen for all of the <td> instead. Details on implementing the pattern is commented in demo as well as alternative methods to use that are more specialized, less verbose, and more efficient.

在演示中评论的详细信息

/*
Register the first (and only) form to submit event
Look for a node with class .destroy and if present remove it from
DOM.
Call makeGrid()
*/

document.forms[0].addEventListener('submit', function(e) {

  const destroy = document.querySelector('.destroy');

  if (destroy) {
    destroy.parentNode.removeChild(destroy);
  }
  makeGrid(e);

});


function makeGrid(ev) {

  ev.preventDefault();

  /* 
  Since there's a form with multiple form controls we are using
  HTMLFormControlsCollection API.
  Just reference the forms HTMLCollection once...
  */
  var ui = document.forms[0].elements;

  /* 
  ...and then use that reference any and every form control
  nested within that referenced form. (colorPicker was moved into
  the form)
  */
  var rowsQty = ui.inputHeight.value;
  var cellsQty = ui.inputWidth.value;
  var cellColor = ui.colorPicker.value;
  var body = document.getElementById("pixelCanvas");
  var table = document.createElement('TABLE');

  /*
  There's 2 loops: 
  1. first loop: the insertRow() method is used once on each loop. 
     insertRow() advantage is that it creates and appends with one
     call.
  */
  for (let r = 0; r < rowsQty; r++) {

    var rowObj = table.insertRow();

    /*
    2. second loop: the insertCell() method is used as many times
       as the submited number (cellsQty). insertCell() also 
       creates and appends in one call as well.
    */
    for (let c = 0; c < cellsQty; c++) {

      var cellObj = rowObj.insertCell();

    }

  }

  /*
  We will use Event Delegation so that we only need to register
  the parent node (table) to listen for an event not only for
  itself but for all of the nodes nested within it. BTW, this 
  works perfectly for dynamically created nodes when the number
  of nodes is unknown....
  */
  // Here we are registering table to listen for clicks...
  table.addEventListener('click', function(e) {

    // Reference the origin of event (clicked td)
    var tgt = e.target;
    // Reference the node registered to the event (table)
    var cur = e.currentTarget;

    // if the clicked node IS NOT the table...
    if (tgt !== cur) {

      // ...change its background to whatever value colorPicker has
      tgt.style.background = cellColor;

    }
  });
  // Mark table for reset
  table.classList.add('destroy');

  // Add completed table to DOM
  body.appendChild(table);

}

body {
  text-align: center;
}

h1 {
  font-family: Monoton;
  font-size: 70px;
  margin: 0.2em;
}

h2 {
  margin: 1em 0 0.25em;
}

h2:first-of-type {
  margin-top: 0.5em;
}

table,
tr,
td {
  border: 1px solid black;
  padding: 25px;
}

table {
  border-collapse: collapse;
  margin: 0 auto;
}

input[type=number] {
  width: 6em;
}

<!DOCTYPE html>
<html>

<head>
  <title>Pixel Art Maker!</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <h1>Pixel Art Maker</h1>

  <h2>Choose Grid Size</h2>
  <form id="sizePicker">
    Grid Height:
    <input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:
    <input type="number" id="inputWidth" name="width" min="1" value="1">
    <input type="submit" value="submit">


    <h2>Pick A Color</h2>
    <input type="color" id="colorPicker">
  </form>
  <h2>Design Canvas</h2>
  <table id="pixelCanvas"></table>

  <script src="designs.js"></script>
</body>

</html>

这篇关于单击单个单元格并使用Javascript将颜色添加到HTML表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆