【发布时间】:2022-01-07 09:05:16
【问题描述】:
情况:我正在尝试创建一个动态输入框,我可以在其中将单词添加到一个框中,让它们单独显示在气泡中。为此,我试图让一个 div 容器 () 与一个输入字段 () 并排放置,因此当用户添加一个元素时,它会将其放在并排显示的 div 容器中。如果您对我想要实现的目标感到困惑,我发布了一个 jsfiddle 以供参考。
我的问题:当我将一个元素添加到 div 容器时,它会将容器的大小扩大到超过我尝试为其分配的最大大小。我为包含所有内容的父 div 设置了特定大小。我认为我的问题在于,对输入框使用 width=100% 引用了父 div,尽管并排添加了新元素,但它不会改变。如何使输入文本框动态调整自身大小以填充剩余空间而不是更多?
我的目标:弄清楚当兄弟元素并排添加到父容器时,如何使输入框动态调整大小以适应父容器。
任何帮助将不胜感激。
代码片段:
$('.emotionsInput').keypress(function (e) {
var key = e.which;
if (key == 13)
{
var inputWord = $(this).val();
var currentCell = $(this);
createTag(currentCell);
}
})
function createTag(currentCell)
{
var parentCell = currentCell.parent()
var inputWord = currentCell.val();
currentCell.val("");
var newTagHTML = '<span class="emotionTag">' + inputWord + '</span>';
parentCell.children(".emotionTagsDiv").append(newTagHTML);
}
#testTagBox > span > span {
border-color:transparent;
box-shadow:0 0 0 2px #000;
border-radius: 40px;
padding:5px;
background-color: white;
width: 100%;
display:flex; /* changed this here, it was inline*/
}
#testTagBox > span {
padding: 0.67rem 0.5rem;
width: 100%;
display:flex; /* changed this here, it was inline-block */
}
#testTagBox {
width: 30rem;
padding-right:1.8rem;
}
.emotionsDiv {
display: flex; /* changed this here, it was inline-block */
width: 100%;
white-space: nowrap;
}
.emotionTagsDiv {
flex: 1 1 auto; /* added this here */
white-space: nowrap;
}
.emotionTag {
display: inline-block;
padding-right: 1em;
}
input {
font-family: Arial;
display: flex; /* changed this here */
flex: 20 1 auto; /* added this so that it prioritizes shrinking this element.*/
width: 100%;
}
input:focus {
outline: none;
}
<html lang="en">
<body>
<div id="testTagBox">
<span>
<span>
<div class="emotionsDiv">
<div class="emotionTagsDiv">
</div>
<input class="emotionsInput" placeholder="type and press enter here" type="text" value="">
</div>
</span>
</span>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@popperjs/core@2/dist/umd/popper.min.js"></script>
<script src="https://unpkg.com/tippy.js@6/dist/tippy-bundle.umd.js"></script>
<script src="testapp.js" type="text/javascript" ></script>
</body>
</html>
如您所见,当您添加一个元素时,当我尝试将输入框固定在右侧并减小左侧大小时,整个容器会调整大小,以便容器保持相同大小并且一切都适合.
【问题讨论】:
标签: javascript html jquery css