添加input元素时Div自动扩展的无固定宽度解决方案咨询
解决动态添加input时容器宽度持续增长的问题
问题根源在于:容器#fields的宽度是自适应内部元素的,而input设置了width:100%,默认盒模型下,input的宽度计算不包含自身的内边距、边框,再加上容器的padding,导致每次添加新input时,浏览器会重新计算容器宽度,进而出现缓慢增长的情况。
下面是几种不需要给容器指定固定宽度的解决办法:
方法一:修改input的盒模型(最推荐)
给input添加box-sizing: border-box,让input的width:100%包含自身的内边距和边框,这样就不会超出容器内容区的宽度,容器也就不会被撑大:
#fields input { width: 100%; box-sizing: border-box; /* 关键代码 */ }
方法二:让容器宽度基于初始内容固定
利用fit-content属性,让容器宽度固定为初始input的宽度,后续添加的input会自动适配这个宽度:
#fields { background: green; padding: 20px; width: fit-content; /* 基于初始内容确定宽度 */ white-space: nowrap; /* 确保input不换行 */ } #fields input { width: 100%; box-sizing: border-box; /* 配合使用更稳妥 */ }
方法三:用flex布局约束容器宽度
给容器设置flex垂直布局,让内部input都拉伸填满容器宽度,同时容器宽度由初始内容决定:
#fields { background: green; padding: 20px; display: flex; flex-direction: column; align-items: stretch; width: fit-content; } #fields input { box-sizing: border-box; }
完整可运行代码示例(方法一)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="fields"> <input type="text"> </div> <style> body { background: grey; display: flex; align-items: center; justify-content: center; } #fields { background: green; padding: 20px; } #fields input { width: 100%; box-sizing: border-box; } </style> <script> setInterval(function() { var input = '<input type="text">'; $("#fields").append(input); }, 2000); </script>
内容的提问来源于stack exchange,提问作者Vans
相关产品推荐
相关产品推荐

