原生js实现textarea自动大小

代码语言:html

所属分类:表单美化

代码描述:原生js实现textarea自动大小

代码标签: textarea 自动 大小

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

<style>
body {
  font-family: Arial, sans-serif;
  padding: 0 20px;
}

h2 {
  font-size: 30px;
}

main {
  text-align: center;
  margin: 0 auto;
  max-width: 800px;
}

textarea {
  color: #444;
  padding: 5px;
}

/* TEXTAREA AUTO RESIZE STYLES BEGIN */

/* The .hiddendiv styles are added with JS.
   You can remove the JS lines and use CSS instead
.hiddendiv {
  display: none;
  white-space: pre-wrap;
  word-wrap: break-word;
}*/

/* the styles for 'txta' are applied to both the textarea and the hidden clone */
/* these must be the same for both */
.txta {
  width: 100%;
  max-width: 500px;
  min-height: 100px;
  font-family: Arial, sans-serif;
  font-size: 16px;
  overflow: hidden;
  line-height: 1.4;
}
/* TEXTAREA AUTO RESIZE STYLES END */
</style>

</head>
<body translate="no">
<main>
<h2>原生js实现Textarea自动大小</h2>
<textarea placeholder="输入多行文字试试" class="txta"></textarea>


</main>

<script>
// Targets all textareas with class "txta"
let textareas = document.querySelectorAll('.txta'),
hiddenDiv = document.createElement('div'),
content = null;

// Adds a class to all textareas
for (let j of textareas) {
  j.classList.add('txtstuff');
}

// Build the hidden div's attributes

// The line below is needed if you move the style lines to CSS
// hiddenDiv.classList.add('hiddendiv');

// Add the "txta" styles, which are common to both textarea and hiddendiv
// If you want, you can remove those from CSS and add them via JS
hiddenDiv.classList.add('txta');

// Add the styles .........完整代码请登录后点击上方下载按钮下载查看

网友评论0