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

HTML DOM Input Button Object: สร้างและจัดการปุ่ม

HTML DOM Input Button Object แทนอิลิเมนต์ <input type="button"> ใช้สร้างและจัดการปุ่มผ่าน JavaScript

รูปแบบการสร้าง (Syntax)

var newButton = document.createElement("INPUT");
newButton.setAttribute("type", "button"); // หรือ "submit", "reset"

คุณสมบัติหลัก (Properties)

คุณสมบัติคำอธิบาย
autofocusคืนค่าและกำหนดโฟกัสอัตโนมัติ
defaultValueคืนค่าและแก้ไขค่าเริ่มต้นของปุ่ม
disabledคืนค่าและกำหนดสถานะปิดใช้งาน
formคืนค่ารีเฟอร์เรนซ์ของฟอร์มที่ครอบคลุมปุ่ม
nameคืนค่าและแก้ไขแอตทริบิวต์ name
typeคืนค่าประเภทปุ่ม (button, submit, reset)
valueคืนค่าและแก้ไขข้อความบนปุ่ม

ตัวอย่างการใช้งาน

สร้างปุ่มเลียนแบบ (replicate) เมื่อคลิก:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; }
        .btn { display: block; margin: 1rem auto; background-color: #db133a; color: #fff; border: 1px solid #db133a; padding: 0.5rem; border-radius: 50px; width: 60%; font-weight: bold; }
        .show-msg { font-weight: bold; font-size: 1.4rem; color: #ffc107; }
    </style>
</head>
<body>
    <h1>ตัวอย่าง Input Button Object</h1>
    <input type="button" onclick="createReplica()" class="btn" value="คลิกเพื่อเลียนแบบฉัน">
    <div class="show-msg"></div>
    <script>
        function createReplica() {
            var newButton = document.createElement("INPUT");
            newButton.setAttribute("type", "button");
            newButton.setAttribute("class", "btn");
            newButton.setAttribute("value", "คลิกเพื่อเลียนแบบฉัน");
            newButton.setAttribute("onclick", "createReplica()");
            document.body.appendChild(newButton);
        }
    </script>
</body>
</html>

ประเภทปุ่ม (type attribute)

ประเภทคำอธิบาย
buttonปุ่มทั่วไป ไม่มีพฤติกรรมเริ่มต้น ต้องใช้ JS ควบคุม
submitส่งฟอร์ม (พฤติกรรมเริ่มต้น)
resetรีเซ็ตฟอร์มกลับค่าเริ่มต้น