我在这里和其他网站上阅读了大量有关如何根据内容动态增加输入字段宽度的资料。到目前为止,所有解决方案都只起到了部分作用,但我找到了一个完美运行的网站:
https://paper.fiftythree.com/search
他们甚至给出了一些关于他们是如何做到的模糊指示:
http://making.fiftythree.com/fluid-text-inputs/
但我一辈子都想不出如何在我自己的网站上实现这一点。
这是我目前的表单结构:
<form action="/" class="search-form">
<input type="text" name="s" class="_input" placeholder="What are you looking for?">
<button type="submit" class="_button">Search</button>
</form>
我尝试这样做的原因是表单作为一个整体在其下方有一个边框。然后我希望输入的文本有自己的底部边框“增长”,文本颜色不同。输入字段的宽度较小,有自己的边框,但我仍然无法获得流畅的动态体验。
有人能帮忙吗?谢谢。
最佳答案
在这个例子中我们可以这样做:
- Input positioned absolute with fixed
width
这永远不会改变,并且会获取数据 - 一个元素,它会根据输入的值和透明文本更改
宽度
,这样我们就只能看到输入文本。 - 居中元素创造宽度增加的错觉
$('input').on('keypress', function() {
$('span').text($(this).val())
})
.container {
text-align: center;
position: relative;
font-size:25px;
}
.container img, .container span {
display: inline-block;
line-height: 50px;
margin-right: -4px;
vertical-align: middle;
}
.container span {
padding: 0 10px;
font-family: sans-serif;
color: transparent;
overflow: hidden;
white-space: nowrap;
max-width: 250px;
}
.container input {
width: 250px;
border: none;
text-align: center;
font-size:inherit;
padding: 0 50px;
position: absolute;
left: 50%;
top: 50%;
z-index: 5;
background: transparent;
transform: translate(-50%, -50%)
}
input:focus {
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<img src="http://placekitten.com/50" alt="">
<span>Type here</span>
<input type="text" placeholder="Type here">
<img src="http://placekitten.com/50" alt="">
</div>
注意:删除文本时仍然会出现一些问题,但你明白了
关于javascript - 解码这个动态增加输入宽度的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41022370/