[英]How to make textbox and text fit inside table cell?
I'm trying to fit a TextBox and text inside table cell but each time I set TextBox width to 100% the falls out off line. 我试图在表格单元格中容纳一个TextBox和文本,但是每次我将TextBox宽度设置为100%时都会掉线。 Right now I'm putting the TextBox and text on separate cells, but if I could make them stay on the same cell without the text falling out of line that would be great.
现在,我将TextBox和文本放在单独的单元格上,但是如果我能使它们保持在同一单元格上,而文本不会掉线,那将会很棒。 Text length may vary so I can't really set TextBox width to a specific %.
文本长度可能会有所不同,因此我无法真正将TextBox宽度设置为特定的百分比。
*Sample Current: |TextBox|Sample Text| *样本当前:|文本框|样本文本|
*Sample Desired: |TextBox Sample Text| *所需样本:| TextBox样本文本|
*Sample with my current code, both TextBox and text in one table cell *我当前的代码示例,一个表单元格中的文本框和文本
|TextBox |文本框
Sample Text | 示例文字|
Currently this is what I'm using to resize the TextBox to fit table td: 当前,这是我用来调整TextBox大小以适合表td的内容:
var tbls1 = [
'tbl-nutritional-histo',
];
for (var tt = 0; tt < tbls1.length; tt++) {
var tbl1 = document.getElementById(tbls1[tt]).getElementsByTagName('input');
// Loop inside elements of current table
for (var ii = 0 ; ii < tbl1.length; ii++) {
// Check if current element is textbox
if (tbl1[ii].type == "text") {
// Set textbox size to 100%
tbl1[ii].style.width = '100%';
}
}
}
'100%' works only when the element's parent element's size is set or inherited. 仅当设置或继承了元素的父元素的大小时,“ 100%”才有效。 You many explore you web page in a debug tool, like fire bug in firefox or developer tool in Chrome, to see the css settings of the related elements.
您可以使用调试工具(例如firefox中的fire bug或Chrome中的开发人员工具)浏览网页,以查看相关元素的css设置。
This is what I came up with, lengthy but solves my problem. 这是我想出的,很长,但是解决了我的问题。 I'll appreciate revisions on my code.
我会感谢对我的代码进行的修订。
REFERENCES: Getting pure text Get offsetWidth 参考: 获取纯文本 获取offsetWidth
<html>
<head>
<style type="text/css">
input[type="text"] {
width: 100%;
}
table td {
border: 1px solid #000;
}
</style>
</head>
<body>
<table id="tbl-test">
<tr>
<td><input type="text">Hello World</td>
<td>Plain Text<input type="text"></td>
</tr>
</table>
<script type="text/javascript">
var tbl = ['tbl-test'];
// Loop thru tbl list
for (var i=0; i <tbl.length;i++) {
var tblElements = document.getElementById(tbl[i])
var tblRowCount = tblElements.rows.length
// Loop thru table rows
for (var rows=0; rows<tblRowCount; rows++) {
var colCount = tblElements.rows[rows].cells.length
// Loop thru table row columns
for (var ii=0; ii<colCount;ii++) {
var el = tblElements.rows[rows].cells[ii]
var inputEl = tblElements.rows[rows].cells[ii].getElementsByTagName('input');
var text = el.innerText || el.textContent;
// Loop thru elements with tags input
for (var t=0; t<inputEl.length;t++) {
if (inputEl[t].type == 'text') {
// Get td size - length of text
inputEl[t].style.width = el.offsetWidth-(text.length) + "px";
}
}
}
}
}
</script>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.