class binding และ css binding ใน KnockoutJS ใช้เพื่อเพิ่มหรือลบคลาส CSS จากองค์ประกอบ DOM ที่เกี่ยวข้อง คลาสเหล่านี้สามารถใช้เพื่อปรับแต่งลักษณะที่ปรากฏขององค์ประกอบ UI ของคุณ
Syntax ของ class binding คือ:
| 1 | data-bind="class: property" | 
โดยที่ property คือชื่อของคุณสมบัติในโมเดลของคุณที่เก็บรายการคลาส CSS
ตัวอย่างเช่น:
| 1 | <div data-bind="class: myClass"></div> | 
สิ่งนี้จะผูกค่าของคุณสมบัติ myClass ในโมเดลของคุณกับรายการคลาส CSS ของ div
เมื่อ myClass เปลี่ยนแปลง รายการคลาส CSS ของ div จะเปลี่ยนแปลงตาม
CSS binding เป็นรูปแบบหนึ่งของ class binding ที่รองรับการแสดงรายการคลาส CSS ด้วยเครื่องหมายจุลภาคคั่น
Syntax ของ CSS binding คือ:
| 1 | data-bind="css: { property: value }" | 
โดยที่ property คือชื่อของคุณสมบัติในโมเดลของคุณที่เก็บรายการคลาส CSS และ value คือค่าของคุณสมบัตินั้น
ตัวอย่างเช่น:
| 1 | <div data-bind="css: { active: isActive }" /> | 
สิ่งนี้จะผูกค่าของคุณสมบัติ isActive ในโมเดลของคุณกับรายการคลาส CSS ของ div
เมื่อ isActive เป็นจริง คลาส active จะถูกเพิ่มลงในรายการคลาส CSS ของ div
เมื่อ isActive เป็นเท็จ คลาส active จะถูกลบออกจากรายการคลาส CSS ของ div
class binding และ CSS binding เป็นเครื่องมือที่ทรงพลังที่สามารถใช้ในการปรับแต่งลักษณะที่ปรากฏขององค์ประกอบ UI ของคุณ การใช้ class binding และ CSS binding คุณสามารถทำให้แอปพลิเคชันของคุณดูน่าดึงดูดยิ่งขึ้นและใช้งานง่ายยิ่งขึ้น
Here are some examples of how you can use class binding and CSS binding in KnockoutJS:
- You can use class binding to highlight an element when it is selected:
| 1 | <div data-bind="class: selected"></div> | 
- You can use CSS binding to change the color of an element when it is in a certain state:
| 1 | <div data-bind="css: { color: backgroundColor }" /> | 
- You can use class binding and CSS binding together to create complex styling effects:
| 1 | <div data-bind="class: { active: isActive }, css: { color: textColor }" /> | 
class binding and CSS binding are powerful tools that can be used to customize the appearance of your KnockoutJS applications.