35

让pre和textarea等HTML元素去掉滚动条自动换行自适应文本内容高度

 5 years ago
source link: https://www.tuicool.com/articles/aqAzuez
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

HTML中pre和textarea可以显示预格式化的文本。即保留空格和换行符。而不必添加<br>和&nbsp;等HTML元素来添加换行和打印空格。

pre去掉滚动条

pre显示文本内容时是不会自动换行的,此时可以添加一些CSS来解决:

<pre>ourjs this is very very very very very very very very very very very very very very very logn contents.</pre>
pre {
    word-wrap: break-word;
    white-space: pre-wrap;

    padding: 9.5px;
    background-color: #f5f5f5;
    border: 1px solid #ccc;
}

textarea让高度自适应内容高度

textarea也能跟prev一样保留内容格式,但是元素高度是固定的,并且无法用CSS来调整。此时可以借助scrollHeight这个属性。

var textarea = document.getElementsByTagName('textarea')[0];
textarea.setAttribute('style','height:'+(textarea.scrollHeight + 12)+'px');

这里加了12px的padding。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK