Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ทำให้ HTML Text Input Field ขยายตามข้อความที่พิมพ์ด้วย JavaScript

วิธีทำ

ใช้ <span> แทน input field ตั้งค่า contenteditable="true" เพื่อให้พิมพ์ได้

ตัวอย่างโค้ด

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <title>Document</title> 
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> 
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css"> 
  <style> 
    span{ border: solid 2px skyblue; } 
    div{ max-width: 500px; } 
  </style> 
</head> 
<body> 
  <div> 
    <span contenteditable="true">John Smith</span> 
  </div> 
  <script> </script> 
</body> 
</html>

วิธีรัน

บันทึกไฟล์ชื่อ "anyName.html" คลิกขวาเลือก "Open with Live Server" ใน VS Code

ผลลัพธ์

ทำให้ HTML Text Input Field ขยายตามข้อความที่พิมพ์ด้วย JavaScript

คำอธิบาย

contenteditable attribute ทำให้ element ใดๆ แก้ไขได้เหมือน input field span จะขยายตัวตามเนื้อหาอัตโนมัติ ไม่ต้องเขียน JavaScript เพิ่มเติม