<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>簡易行番号付きエディタ</title>
<style>
/* レイアウトの基本設定 */
.editor-container {
display: flex;
width: 100%;
max-width: 600px;
height: 300px;
border: 1px solid #ccc;
font-family: 'Courier New', Consolas, monospace; /* 等幅フォント必須 */
font-size: 16px;
line-height: 1.5;
background-color: #f5f5f5;
}
/* 行番号エリア */
#line-numbers {
width: 50px;
padding: 10px 5px;
text-align: right;
background-color: #e0e0e0;
color: #888;
border-right: 1px solid #ccc;
overflow: hidden; /* スクロールバーを出さない */
user-select: none; /* 選択できないようにする */
box-sizing: border-box;
}
/* テキストエリア */
#text-input {
flex: 1; /* 残りの幅を全部使う */
padding: 10px;
border: none;
outline: none;
resize: none; /* サイズ変更を無効化 */
white-space: pre; /* 自動折り返しをしない(簡易化のため) */
overflow: auto; /* スクロール許可 */
background-color: #fff;
color: #333;
box-sizing: border-box;
/* 行番号とフォント設定を完全に一致させる */
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
/* 現在の行のハイライト(行番号側) */
.current-line {
color: #fff;
background-color: #007bff;
font-weight: bold;
border-radius: 4px;
padding-right: 2px;
}
</style>
</head>
<body>
<h3>行番号・カーソル位置表示サンプル</h3>
<div class="editor-container">
<div id="line-numbers">1</div>
<textarea id="text-input" placeholder="ここに入力してください..."></textarea>
</div>
<script>
const textarea = document.getElementById('text-input');
const lineNumbersEle = document.getElementById('line-numbers');
// 行番号を更新する関数
const updateLineNumbers = () => {
// 改行の数から行数を計算
const lines = textarea.value.split('\n').length;
// カーソル位置から現在の行を計算
// カーソル位置までの文字列を切り出し、その中の改行数を数える
const cursorPosition = textarea.selectionStart;
const currentLine = textarea.value.substr(0, cursorPosition).split('\n').length;
// 行番号のHTMLを生成
let linesHTML = '';
for (let i = 1; i <= lines; i++) {
if (i === currentLine) {
// 現在の行にはクラスを付与
linesHTML += `<div class="current-line">${i}</div>`;
} else {
linesHTML += `<div>${i}</div>`;
}
}
lineNumbersEle.innerHTML = linesHTML;
};
// スクロールを同期する関数
const syncScroll = () => {
lineNumbersEle.scrollTop = textarea.scrollTop;
};
// イベントリスナーの設定
textarea.addEventListener('input', updateLineNumbers); // 入力時
textarea.addEventListener('keyup', updateLineNumbers); // カーソル移動時(キー操作)
textarea.addEventListener('click', updateLineNumbers); // カーソル移動時(クリック)
textarea.addEventListener('scroll', syncScroll); // スクロール時
// 初期化
updateLineNumbers();
</script>
</body>
</html>
使用変数
| charset | |
| class | |
| content | |
| currentLine | |
| cursorPosition | |
| i | |
| id | |
| innerHTML | |
| lang | |
| lineNumbersEle | |
| lines | |
| linesHTML | |
| name | |
| placeholder | |
| scale | |
| scrollTop | |
| syncScroll | |
| textarea | |
| updateLineNumbers | |
| width |