<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>現在の行数表示サンプル</title>
<style>
body {
font-family: sans-serif;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
}
textarea {
width: 100%;
height: 200px;
padding: 10px;
font-size: 16px;
line-height: 1.5;
box-sizing: border-box;
resize: vertical; /* 縦方向のみリサイズ許可 */
}
/* 行数表示エリアのデザイン */
.status-bar {
margin-top: 5px;
text-align: right; /* 右寄せにする */
font-size: 14px;
color: #555;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h3>自動折り返しテキストエリア</h3>
<textarea id="myTextarea" placeholder="ここに文字を入力してください..."></textarea>
<div class="status-bar">
Line: <span id="lineCount">1</span>
</div>
</div>
<script>
const textarea = document.getElementById('myTextarea');
const lineCountSpan = document.getElementById('lineCount');
const updateLineCount = () => {
// 1. カーソルの位置(何文字目か)を取得
const cursorPosition = textarea.selectionStart;
// 2. テキストの先頭からカーソル位置までの文字列を取得
const textUpToCursor = textarea.value.substr(0, cursorPosition);
// 3. その文字列の中に「改行(\n)」がいくつあるか数える
// (改行の数 + 1 が現在の行数になります)
const currentLine = textUpToCursor.split('\n').length;
// 4. 画面に表示
lineCountSpan.textContent = currentLine;
};
// 入力時、キー操作時、クリック時に更新を実行
textarea.addEventListener('input', updateLineCount);
textarea.addEventListener('keyup', updateLineCount); // 矢印キー移動に対応
textarea.addEventListener('click', updateLineCount); // マウスクリック移動に対応
</script>
</body>
</html>
使用変数
| charset | |
| class | |
| content | |
| currentLine | |
| cursorPosition | |
| id | |
| lang | |
| lineCountSpan | |
| name | |
| placeholder | |
| scale | |
| textarea | |
| textContent | |
| textUpToCursor | |
| updateLineCount | |
| width |