gpt4 book ai didi

javascript - <textarea> 的灵活高度作为新的换行符

转载 作者:技术小花猫 更新时间:2023-10-29 12:05:40 29 4
gpt4 key购买 nike

我以前从未见过这种做法,但我希望它可以做到。我正在尝试在其中写入文本时自动设置文本区域的高度。如此处所见...

http://i.stack.imgur.com/oxRfj.jpg

http://i.stack.imgur.com/XVzYT.jpg

希望这些图片能解释我的意思。第二张图片也显示了它的理论最大高度。

https://jsfiddle.net/nupk26Ly/

.text-f {
border: none;
border-bottom: #183A4C solid 1px;
color: #183A4C;
font: 1rem/2.4rem Georgia, serif;
margin-top: 40px;
resize: none;
height: 40px;
width: 100%;
}

最佳答案

这是一个使用 jquery 的解决方案。希望对您有所帮助。

function h(e) {
$(e).css({'height':'40','overflow-y':'hidden'}).height(e.scrollHeight);
}
$('textarea').each(function () {
h(this);
}).on('input', function () {
h(this);
});
.text-f {
border: none;
border-bottom: #183A4C solid 1px;
color: #183A4C;
font: 1rem/2.4rem Georgia, serif;
margin-top: 40px;
height: 40px;
width: 100%;
}

.form-btn {
background: #183A4C;
border: solid 1px #183A4C;
color: #fff;
cursor: pointer;
display: block;
font: 1rem/1.333rem Georgia, serif;
height: 30px;
width: 140px;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea name="Message" class="text-f" placeholder="Describe your project..."></textarea>

<button class="form-btn" type="button">Submit</button>

纯Javascript解决方案(PS:我在textarea标签中添加了一个ID(textarea))

var textarea = document.getElementById("textarea");

textarea.oninput = function() {
textarea.style.height = "";
/* textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px"; */
textarea.style.height = textarea.scrollHeight + "px"
};
.text-f {
border: none;
border-bottom: #183A4C solid 1px;
color: #183A4C;
font: 1rem/2.4rem Georgia, serif;
width: 100%;
resize: none;
height: 40px;
}
<div id="content">
<div id="main-headline">
<h1 class="main-header">Fill out the form or contact me alternatively.</h1>
</div>

<!----- content ------>
<div class="content-container">
<!----- row 1 ------>
<section class="row">
<!----- form ------>
<form name="contact-f" action="#" method="post">
<div class="col-3 c-right-col">
<textarea id="textarea" name="Message" class="text-f" placeholder="Describe your project..."></textarea>
<button class="link-btn form-btn" type="button">Submit</button>
</div>
</form>
</section>
</div>
</div>

关于javascript - &lt;textarea&gt; 的灵活高度作为新的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38472424/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com