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

แอตทริบิวต์เหตุการณ์ onsearch ใน HTML

แอตทริบิวต์เหตุการณ์ onsearch ใน HTML ถูกกระตุ้นเมื่อผู้ใช้กดปุ่ม "Enter" ในองค์ประกอบ input HTML ที่มี type="search" ในเอกสาร HTML

ไวยากรณ์

<input type="search" onsearch="script">

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
<style>
  body { color: #000; height: 100vh; background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat; text-align: center; padding: 20px; }
  input { border: 2px solid #fff; background: transparent; height: 2rem; padding: 10px; width: 200px; }
  ::placeholder { color: #000; }
  .show { font-size: 1.5rem; font-weight: bold; }
</style>
</head>
<body>
<h1>ตัวอย่างแอตทริบิวต์เหตุการณ์ onsearch ของ HTML</h1>
<input type="search" onsearch="searchFn()" placeholder="ค้นหาที่นี่">
<p>ป้อนข้อความค้นหาแล้วกดปุ่ม "Enter"</p>
<div class="show"></div>
<script>
  function searchFn() {
    document.body.style.background = "linear-gradient(45deg, #8BC6EC 0%, #9599E2 100%) no-repeat";
    document.querySelector(".show").innerHTML = "คุณค้นหา: " + document.querySelector("input").value;
  }
</script>
</body>
</html>

ผลลัพธ์

ป้อนข้อความค้นหาในช่องค้นหาแล้วกด "Enter" เพื่อดูการทำงานของ onsearch

จะแสดง "คุณค้นหา: [ข้อความที่ค้นหา]" และเปลี่ยนพื้นหลัง