Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tự động co giãn textarea (Auto-resize) bằng JavaScript

Kỹ thuật cốt lõi

Khi người dùng nhập text, điều chỉnh height của textarea bằng scrollHeight (chiều cao nội dung thực tế).

function autoResize(textarea) {
    textarea.style.height = 'auto';           // Reset để co lại khi xóa text
    textarea.style.height = textarea.scrollHeight + 'px'; // Mở rộng khớp nội dung
}

Ví dụ hoàn chỉnh

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Auto-resize Textarea</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; max-width: 600px; margin: 0 auto; }
        textarea.resizeArea { 
            width: 100%; 
            min-height: 100px; 
            padding: 12px; 
            font-family: inherit; 
            font-size: 16px; 
            line-height: 1.5;
            border: 2px solid #ddd; 
            border-radius: 8px; 
            resize: none; /* Tắt resize handle mặc định */
            box-sizing: border-box;
            transition: height 0.1s ease;
        }
        textarea.resizeArea:focus { border-color: #1976d2; outline: none; box-shadow: 0 0 0 3px rgba(25,118,210,0.1); }
        .hint { color: #666; font-size: 14px; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>Tự động co giãn Textarea</h1>
    <textarea class="resizeArea" placeholder="Gõ hoặc dán văn bản dài vào đây... textarea sẽ tự mở rộng"></textarea>
    <p class="hint">Thử dán một đoạn văn bản dài (Ctrl+V) để xem hiệu ứng</p>

    <script>
        const textarea = document.querySelector('.resizeArea');
        
        function resizeTextArea() {
            this.style.height = 'auto';
            this.style.height = this.scrollHeight + 'px';
        }
        
        // Lắng nghe sự kiện input (bao gồm paste, cut, typing)
        textarea.addEventListener('input', resizeTextArea);
        
        // Khởi tạo chiều cao ban đầu
        resizeTextArea.call(textarea);
    </script>
</body>
</html>

Nâng cao: Giới hạn chiều cao tối đa

function autoResize(textarea) {
    textarea.style.height = 'auto';
    const height = Math.min(textarea.scrollHeight, 300); // Max 300px
    textarea.style.height = height + 'px';
    textarea.style.overflowY = textarea.scrollHeight > 300 ? 'auto' : 'hidden';
}

Xử lý nhiều textarea

document.querySelectorAll('textarea.auto-resize').forEach(textarea => {
    textarea.addEventListener('input', function() {
        this.style.height = 'auto';
        this.style.height = this.scrollHeight + 'px';
    });
    // Trigger initial resize
    textarea.dispatchEvent(new Event('input'));
});

CSS-only Alternative (Hạn chế)

/* Chỉ hoạt động trên Firefox với field-sizing: content */
textarea {
    field-sizing: content; /* CSS mới, hỗ trợ hạn chế */
}

Lưu ý

  • Set box-sizing: border-box để padding không ảnh hưởng chiều cao
  • Tắt resize: none để tránh conflict với handle mặc định
  • Dùng input event thay keyup để bắt paste, drag-drop, autocomplete
  • Transition CSS tạo hiệu ứng mượt mà