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

ระบุว่าเนื้อหาควรแปลหรือไม่ด้วยแอตทริบิวต์ translate ใน HTML

แอตทริบิวต์ translate ใช้บอกเครื่องมือแปลภาษาอัตโนมัติ (เช่น Google Translate, Bing Translator, เบราว์เซอร์ built-in translation) ว่าเนื้อหาขององค์ประกอบควรแปลหรือไม่

ค่าที่ใช้ได้

ค่า ความหมาย
yes เนื้อหาควรถูกแปล (ค่าเริ่มต้น)
no เนื้อหาไม่ควรถูกแปล

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

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8">
  <title>Translate Attribute Demo</title>
</head>
<body>
  <h1>เว็บไซต์ตัวอย่าง</h1>
  
  <p>ย่อหน้านี้จะถูกแปลเป็นภาษาอื่น (ค่าเริ่มต้น)</p>
  
  <p translate="no">BrandName™ - ชื่อแบรนด์นี้ไม่ควรแปล</p>
  
  <p>รหัสโปรโมชั่น: <span translate="no">TH-SALE-2024</span> - รหัสนี้ห้ามแปล</p>
  
  <div translate="no">
    <h2>โค้ดตัวอย่าง</h2>
    <pre><code>function hello() {
  console.log("Hello World");
}</code></pre>
  </div>
  
  <p>ที่อยู่: 123 ถนนสุขุมวิท แขวงคลองเตย เขตคลองเตย กรุงเทพมหานคร 10110</p>
  
  <footer translate="no">
    © 2024 Company Name. All rights reserved.
  </footer>
</body>
</html>

สิ่งที่ควรตั้ง translate="no"

  • ชื่อแบรนด์/ตรademark (Brand names, trademarks)
  • รหัสโปรโมชั่น/คูปอง (Promo codes, coupons)
  • โค้ดโปรแกรม/คำสั่งเทคนิค (Code snippets, technical commands)
  • ที่อยู่/หมายเลขโทรศัพท์ (Addresses, phone numbers)
  • หน่วยวัด/สัญลักษณ์เฉพาะ (Units, special symbols)
  • ชื่อวิทยาศาสตร์/ชื่อเฉพาะ (Scientific names, proper nouns)
  • อีเมล/URL

การทำงานร่วมกับ CSS

สามารถใช้ CSS selector เพื่อจัดการ translate ได้:

<style>
  /* ป้องกันการแปลทุกอย่างใน code block */
  code, pre, kbd, samp { translate: no; }
  
  /* หรือใช้ class */
  .no-translate { translate: no; }
</style>
หมายเหตุ: translate เป็น global attribute ใช้ได้กับทุกแท็ก HTML และสืบทอดไปยังลูก (inherited) - หากตั้งที่ parent จะมีผลกับ children ทั้งหมด ยกเว้นจะ override ด้วยค่าอื่น

การทดสอบ

ลองเปิดหน้าใน Chrome → คลิกขวา → "แปลเป็นภาษาไทย" (หรือภาษาอื่น) เพื่อดูผลลัพธ์