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

ออบเจ็กต์ PopStateEvent ของ HTML DOM

ออบเจ็กต์ PopStateEvent ของ HTML DOM เป็นตัวจัดการเหตุการณ์ (event handler) สำหรับเหตุการณ์ popstate ซึ่งเกิดขึ้นเมื่อประวัติของหน้าต่าง (window's history) เปลี่ยนแปลง

คุณสมบัติของ PopStateEvent

คุณสมบัติคำอธิบาย
stateคืนค่าออบเจ็กต์ที่แทนสำเนาของรายการในประวัติ

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

ตัวอย่างด้านล่างแสดงการใช้งานออบเจ็กต์ PopStateEvent ของ HTML DOM

<!DOCTYPE html> <html> <head> <style>    html{       height:100%;    }    body{       text-align:center;       color:#fff;       background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;       height:100%;    }    p{       font-size:1.2rem;    }    .btn{       background:#0197F6;       border:none;       height:2rem;       border-radius:2px;       width:35%;       margin:2rem auto;       display:block;       color:#fff;       outline:none;       cursor:pointer;    } </style> </head> <body> <h1>สาธิตเหตุการณ์ DOM PopStateEvent</h1> <button onclick="display()" class="btn">คลิกฉัน</button> <script>    function display(){       window.onpopstate = function(event) {          alert("location: " + document.location +             ", state: " + JSON.stringify(event.state));       };       history.pushState({          page: 1       }, "title home", "?page=home");       history.pushState({          page: 2       }, "title about", "?page=about");       history.replaceState({          page: 3       }, "title contact", "?page=contact");       history.back();       history.back();    } </script> </body> </html>

ผลลัพธ์

โค้ดด้านบนจะให้ผลลัพธ์ดังนี้

ออบเจ็กต์ PopStateEvent ของ HTML DOM

คลิกที่ปุ่ม "คลิกฉัน" เพื่อทำความเข้าใจว่าออบเจ็กต์ PopStateEvent ทำงานอย่างไร

ออบเจ็กต์ PopStateEvent ของ HTML DOM

คลิก "ตกลง"

ออบเจ็กต์ PopStateEvent ของ HTML DOM