HTML input textbox with a width of 100% overflows table cells

前端 未结 14 1547
别那么骄傲
别那么骄傲 2021-01-29 20:28

Does anyone know why the input elements with a width of 100% go over the table\'s cells border.

In the simple example below input box go over the table\'s cells border,

14条回答
  •  无人共我
    2021-01-29 21:08

    With some Javascript you can get the exact width of the containing TD and then assign that directly to the input element.

    The following is raw javascript but jQuery would make it cleaner...

    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++)
    {
        var el = inputs[i];
        if (el.style.width == '100%')
        {
            var pEl = el.parentNode;  // Assumes the parent node is the TD...
            el.style.width = pEl.offsetWidth;
        }
    }
    

    The issues with this solution are:

    1) If you have your inputs contained in another element such as a SPAN then you will need loop up and find the TD because elements like SPANs will wrap the input and show its size rather then being limited to the size of the TD.

    2) If you have padding or margins added at different levels then you might have to explicitly subtract that from [pEl.offsetWidth]. Depending on your HTML structure that can be calculated.

    3) If the table columns are sized dynamically then changing the size of one element will cause the table to reflow in some browsers and you might get a stepped effect as you sequentially "fix" the input sizes. The solution is to assign specific widths to the column either as percentages or pixels OR collect the new widths and set them after. See the code below..

    var inputs = document.getElementsByTagName('input');
    var newSizes = [];
    for (var i = 0; i < inputs.length; i++)
    {
        var el = inputs[i];
        if (el.style.width == '100%')
        {
            var pEl = el.parentNode;  // Assumes the parent node is the TD...
            newSizes.push( { el: el, width: pEl.offsetWidth });
        }
    }
    
    // Set the sizes AFTER to avoid stepping...
    for (var i = 0; i < newSizes.length; i++)
    {
        newSizes[i].el.style.width = newSizes[i].width;
    }
    

提交回复
热议问题