jsÔõô»ñÈ¡classµÄÃû×Ö
Òª»ñÈ¡µ¥¸öÔªËØµÄ class Ãû³Æ£¬¿ÉÒÔʹÓà element.classlist.value ÊôÐÔ¡£Òª»ñÈ¡¶à¸öÔªËØµÄ class Ãû³Æ£¬¿ÉÒÔʹÓà document.queryselectorall() »ñÈ¡ÔªËØÜöÝÍ£¬È»ºó±éÀú¸ÃÜöÝÍ»ñȡÿ¸öÔªËØµÄ class Ãû³Æ¡£±ðµÄ£¬»¹¿ÉÒÔʹÓà classlist ÊôÐÔ¸½¼Ó»òɾ³ý class Ãû³Æ£¬Çл» class Ãû³Æ¡£
ÔõÑùʹÓà JavaScript »ñÈ¡ÔªËØµÄ class Ãû³Æ
»ñÈ¡µ¥¸öÔªËØµÄ class Ãû³Æ
»ñÈ¡µ¥¸öÔªËØµÄ class Ãû³Æ£¬¿ÉÒÔʹÓà element.classList.value ÊôÐÔ¡£
const element = document.querySelector(".my-class"); const className = element.classList.value; console.log(className); // Êä³ö£ºmy-class
µÇ¼ºó¸´ÖÆ
»ñÈ¡¶à¸öÔªËØµÄ class Ãû³Æ
»ñÈ¡¶à¸öÔªËØµÄ class Ãû³Æ£¬¿ÉÒÔʹÓà document.querySelectorAll() ÒªÁì»ñÈ¡ÔªËØÜöÝÍ£¬È»ºó±éÀú¸ÃÜöÝÍ»ñȡÿ¸öÔªËØµÄ class Ãû³Æ¡£
const elements = document.querySelectorAll(".my-class"); for (let element of elements) { const className = element.classList.value; console.log(className); }
µÇ¼ºó¸´ÖÆ
¸½¼Ó»òɾ³ý class Ãû³Æ
³ýÁË»ñÈ¡ class Ãû³ÆÍ⣬»¹¿ÉÒÔʹÓà classList ÊôÐÔ¸½¼Ó»òɾ³ý class Ãû³Æ¡£
¸½¼Ó class Ãû³Æ
ʹÓà classList.add() ÒªÁ츽¼ÓÒ»¸ö»ò¶à¸ö class Ãû³Æ¡£
element.classList.add("new-class");
µÇ¼ºó¸´ÖÆ
ɾ³ý class Ãû³Æ
ʹÓà classList.remove() ÒªÁìɾ³ýÒ»¸ö»ò¶à¸ö class Ãû³Æ¡£
element.classList.remove("old-class");
µÇ¼ºó¸´ÖÆ
Çл» class Ãû³Æ
ʹÓà classList.toggle() ÒªÁìÇл»Ò»¸ö class Ãû³Æ¡£ÈôÊÇÔªËØÒѾßÓиà class Ãû³Æ£¬Ôò½«Æäɾ³ý£»ÈôÊÇÔªËØûÓиà class Ãû³Æ£¬Ôò½«ÆäÌí¼Ó¡£
element.classList.toggle("active");
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÔõô»ñÈ¡classµÄÃû×ÖµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡