javascript 我可以让输入元素填充表格列的宽度吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8612567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:59:17  来源:igfitidea点击:

Can I have an input element fill the width of a table column?

javascripthtmlcssinput

提问by diolemo

I would like an input[type=text] element to always be the same width as the table cell it is contained in. I need to ensure that the width of the table cell is not influenced by the width of the input element.

我希望 input[type=text] 元素始终与包含它的表格单元格的宽度相同。我需要确保表格单元格的宽度不受输入元素宽度的影响。

How can I do this with CSS? Will I need to use JS? If so, what would be the best way to determine when the table cell changed size?

我怎样才能用 CSS 做到这一点?我需要使用JS吗?如果是这样,确定表格单元格何时更改大小的最佳方法是什么?

回答by jerjer

if this does work for you:

如果这对你有用:

td > input[type='text']
{
    width: 100%; /*this will set the width of the textbox equal to its container td*/
}

try this:

试试这个:

td > input[type='text']
{
    display:block; /*this will make the text box fill the horizontal space of the its container td*/
}

回答by dronus

Setting CSS rules width:100%;and display:block;for the INPUTelement should do that.

设置CSS规则width:100%;,并display:block;INPUT元素应该这样做。

In practice, that is not enough, it seems some browsers emphasize the INPUT's sizeattibute over the style. So for example, Chrome widens the element to agree with size, thus widening the table column. Setting size=0doesn't work, as it is defaulted to some valid value then. However, setting size=1attribute at the INPUTelement achives the desired behaveour. However, this is no CSS-only solution, and the INPUTcannot be compressed below a certain but small width.

在实践中,这还不够,似乎有些浏览器强调INPUT'size属性高于样式。例如,Chrome 将元素加宽以符合大小,从而加宽表格列。设置size=0不起作用,因为它默认为某个有效值。但是,size=1INPUT元素上设置属性可以实现所需的行为。然而,这不是 CSS-only 解决方案,并且INPUT不能压缩到一定但很小的宽度以下。

回答by dfsq

Setting width of your field to 100% should work. In this case you will also want to add box-sizingrule to avoid the input field from over ignoring table cell paddings.

将字段的宽度设置为 100% 应该可以。在这种情况下,您还需要添加box-sizing规则以避免输入字段过度忽略表格单元格填充。

td.value input {
    width: 100%;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

See example http://jsfiddle.net/MEARG/

参见示例http://jsfiddle.net/MEARG/

回答by Francesco Belladonna

What about setting style (or class) width: 100%; for input elements that are inside a table?

如何设置样式(或类)宽度:100%;对于表内的输入元素?

Something like this:

像这样的东西:

td input.myclass[type=text]
{
    width: 100%;
}

回答by Ayman Safadi

CSS should do the trick:

CSS 应该可以解决问题:

#my_input {
    width: 100%;
}

#my_table {
    table-layout:fixed;
}