![](/img/trans.png)
[英]How to force Textarea to increase height when a user puts in a line break?
[英]JQUERY: Increase Textarea Height when clicked bug
我有這個文本區域,我想在單擊時增加它的高度,我還在上面添加了DIV:
<div id = "postbox_container">
<textarea id = "post_textarea" rows = "1" cols = "7" name = "text_post" placeholder = "Post..." required/></textarea>
</div>
它是CSS:
box-sizing: border-box;
width: 97%;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 2.7vh;
padding: 1vh;
border: 0px solid #dedede;
resize: none;
transition: all 0.5s ease;
最后我的jQuery:
$(document).ready(function(){
$('#postbox_container').on('click', function(){
$('#post_textarea').height('20vh');
});
});
這可行,但是每次我單擊文本區域時,都會增加一個新的高度-因此單擊得越多,它就會變得越來越長。 我的觀點是,我希望每次用戶首次單擊DIV時,將textarea的高度設置為固定的20vh
。 有想法嗎? 謝謝。
添加一個檢查,這意味着它將僅在第一次單擊時運行:
$(document).ready(function(){
var clicked = false;
$('#postbox_container').on('click', function(){
if (!clicked) {
$('#post_textarea').height('20vh');
clicked = true;
}
});
});
加載頁面后,我們知道尚未單擊該框,那么當我們單擊它時,我們告訴瀏覽器這已經發生並將其設置為true-因此,當再次單擊時,瀏覽器會跳過更改高度的請求。
要將高度重新聚焦:
$( "#post_textarea" )
.focusout(function() {
$('#post_textarea').height('[set the height you want to return to]');
})
您可以使用一個功能進行綁定。 但是我已經測試了您的代碼,對我來說效果很好。
鏈接在這里
https://jsfiddle.net/Saiyam/x91ts87z/5/
$('#postbox_container').one('click', function(){
$('#post_textarea').height('20vh');
});
這將僅綁定一次。
您可以添加一個標志,當用戶單擊該標志時將其更改為“ true”,下一次檢查該標志,並且在該標志為“ true”時不執行任何操作,就像這樣。
var firstTime = false;
$(document).ready(function(){
$('#postbox_container').on('click', function(){
if(!firstTime){
firstTime = true;
$('#post_textarea').height('20vh');
}
});
});
在注釋之后,如果您想讓文本區域在焦點不清晰時恢復其大小,則可以執行以下操作。
我故意對Web Develop Wolf使用一種略有不同的方法(很好的答案,+ 1)來顯示替代方法。
CSS:
#postbox_container {
box-sizing: border-box;
width: 97%;
font-family: 'Open Sans', sans-serif;
font-weight: 300;
font-size: 2.7vh;
padding: 1vh;
border: 0px solid #dedede;
resize: none;
transition: all 0.5s ease;
}
#post_textarea.selected {
height: 20vh;
}
JS:
$(document).ready(function() {
$('#post_textarea').on('focus', function() {
$('#post_textarea').addClass('selected');
});
$('#post_textarea').on('focusout', function() {
$('#post_textarea').removeClass('selected');
});
});
小提琴: https : //jsfiddle.net/q25h394m/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.