Use div to simulate textarea to achieve highly adaptive text input box (attached: js control textarea to achieve highly adaptive text input box), divtextarea

Source: Internet
Author: User

Use div to simulate textarea to achieve highly adaptive text input box (attached: js control textarea to achieve highly adaptive text input box), divtextarea

I. There are many restrictions on using the textarea label to input multi-line text. For example, the high self-adaptability cannot be achieved, and the ugly scroll bar may occur.

A new contenteditable attribute is added to html5. this attribute allows uneditable tags other than input and textarea to be editable;

The usage is as follows:

// Contenteditable = "true" when the attribute value is true, you can write tags into the Editable tags. the styles of copied styles are retained;
<Div contenteditable = "true"> I am an editable Rich Text Box </div>

// Contenteditable = "plaintext-only" when the property value is plaintext-only, only plain text data can be written to the Editable tag. For copied styles, convert to plain text, and filter out style labels and other content;
<Div contenteditable = "plaintext-only"> </div>

 

2. If you do not use this attribute, you can use js to control the height of textarea. The principle is to increase the height of textarea when a scroll bar appears, so that the scroll bar disappears.

How to determine whether a scroll bar exists? When the scrollHeight of an element is greater than offsetHeight, the scroll bar appears;

The implementation method is as follows:

// Html
<Textarea id = "text"> </textarea>

// Css
# Text {
Font-size: 20px;
Overflow: hidden; // required
}

// Js
$ ('# Text'). on ('input', function (){
If (text. scrollHeight> text. offsetHeight ){
THeight + = 20; // The font-size is 20, so the height of textarea is increased by 20 PX each time.
Watermark ('{text'}.css ('height', THeight );
}
})
 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.