简体   繁体   English

扩大/缩小文本打字区域

[英]Expanding/Contracting Textarea on Typing

I am looking to have a comment field that will grow to show all text when the user clicks on it and then shrink back down (hiding the unshowable text) when the user clicks out of the text area. 我希望有一个注释字段,当用户单击它时它将增长为显示所有文本,然后在用户单击文本区域之外时缩小(隐藏无法显示的文本)。 The user should be able to type in text and modify what they see. 用户应该能够输入文本并修改他们看到的内容。

I am assuming that textarea is the way to go since input doesn't have multi-line functionality. 我假设textarea是必经之路,因为输入没有多行功能。 However, I am a little stuck on how to implement this. 但是,我对如何实现这一点有些困惑。 It seems everything out there just has the textarea resize to fit the text but not shrink back down after the user is done typing in it. 似乎所有内容都只是调整了textarea的大小以适合文本,但在用户完成输入后不会缩小。

Could someone help me out/point me in the right direction? 有人可以帮我指出正确的方向吗?

Thanks! 谢谢!

You can use the :focus and :active states to change the textbox once the user clicks on it. 用户单击后,可以使用:focus:active状态更改文本框。 Something like: 就像是:

textarea{
 width: 200px;
 height: 200px;
 resize: none;
}

textarea:focus,
textarea:active{
  width: 400px;
  height: 400px;
}

Once the user clicks into the space, the text box will expand to the new dimensions. 用户单击该空间后,文本框将扩展到新尺寸。 These work very similarly to :hover , if you're familiar with adding hover states. 如果您熟悉添加悬停状态,它们的工作方式与:hover非常相似。

Demo in a jsbin: http://jsbin.com/culil/1/ jsbin中的演示: http ://jsbin.com/culil/1/


To add this stylings to you page you have two options. 要向您的页面添加此样式,您有两个选择。

1: You can include it as a css class in your site's stylesheet: 1:您可以将其作为CSS类添加到网站的样式表中:

Css: CSS:

 .parentcontainer > textarea:focus, .parentcontainer > textarea:active { width: 400px; height: 400px; } 

This is a best practice because it separates the concerns of styling ( which should be CSS ) and adding interactivity ( which should be JavaScript). 这是最佳实践,因为它将样式(应为CSS)和添加交互性(应为JavaScript)的关注点分开了。

2: You can add the class before you append the element using javascript: 2:您可以在使用javascript追加元素之前添加类:

css: CSS:

$(function(){
  var textarea = $(".parentDiv").append("<textarea></textarea>");
  $("textarea").addClass("my-textarea-class"); 
});

js: JS:

 $(function(){ var textarea = $(".parentDiv").append("<textarea></textarea>"); $("textarea").addClass("my-textarea-class"); }); 

http://jsbin.com/buhado/1/edit http://jsbin.com/buhado/1/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM