输入字段

时间:2017-12-11 00:24:50

标签: javascript html css html-table html-input

这与我的相似:



var btn = document.querySelector('button');
btn.addEventListener('click', function() {
  var tdCollection = document.querySelectorAll('td');
  for (var i = 0; i < tdCollection.length; i++) {
  	var field = document.createElement('input');
    field.setAttribute('type', 'text');
    field.setAttribute('name', 'Field');
    field.setAttribute('value', tdCollection[i].textContent);
    tdCollection[i].innerHTML = "";
    tdCollection[i].appendChild(field);
  }
  
});
&#13;
td {
  border: 1px solid black;
}
&#13;
<table>
  <tr>
    <td>A very long text</td>
    <td>tinyTxt</td>
  </tr>
  <tr>
    <td>A very long text</td>
    <td>tinyTxt</td>
  </tr>
</table>
<button name="edit">Edit</button>
&#13;
&#13;
&#13;

即使在按下“编辑”按钮后,我也希望表格单元格保持其原始宽度。将输入字段宽度设置为其父单元格之一是理想的,但也可以将字段宽度调整为其值,并且如果无法将它们固定到单元格宽度,则使用overflow: hidden可能会有效。

感谢您的帮助:D

修改

我试图保留每列的自然宽度,如果有办法,我希望避免每列都有相同的宽度。

1 个答案:

答案 0 :(得分:0)

您可以为tdinput附加td设置固定的高度和宽度。

尝试以下方式:

var btn = document.querySelector('button');
var cellWidth = document.getElementById('myTable').rows[0].cells[0].offsetWidth;
var cellHeight = document.getElementById('myTable').rows[0].cells[0].offsetHeight;
console.log(cellHeight)
btn.addEventListener('click', function() {
  var tdCollection = document.querySelectorAll('td');
  for (var i = 0; i < tdCollection.length; i++) {
  	var field = document.createElement('input');
    field.setAttribute('type', 'text');
    field.setAttribute('name', 'Field');
    field.setAttribute('value', tdCollection[i].textContent);
    field.style.width = (cellWidth - (4 + 4)) + 'px'; // removing approximate border of input element from left and right to fit into td.
    field.style.height = (cellHeight) + 'px'; // removing approximate border of input element from left and right to fit into td.
    tdCollection[i].innerHTML = "";
    tdCollection[i].appendChild(field);
  }
  
});
td {
  border: 1px solid black;
}
/*table td, input {
    width: 100px;
    height: 50px;
    overflow: hidden;
    display: inline-block;
    white-space: nowrap;
}*/
<table id="myTable">
  <tr>
    <td>A very long text</td>
    <td>tinyTxt</td>
  </tr>
  <tr>
    <td>A very long text</td>
    <td>tinyTxt</td>
  </tr>
</table>
<button name="edit">Edit</button>