jsÔõô»ñÈ¡classÀà
ÔÚ javascript ÖлñÈ¡ÀàÃûÓÐÁ½ÖÖÒªÁ죺ʹÓà getattribute(“class”) »ñÈ¡ÀàÃûÊôÐÔÖµ¡£Ê¹Óà classlist ÊôÐÔ»ñÈ¡ domtokenlist ¹¤¾ß²¢Ê¹ÓÃÆäÒªÁì²Ù×÷Àà¡£
ÔõÑùÔÚ JS ÖлñÈ¡Àà
ÔÚ JavaScript ÖУ¬»ñÈ¡Ò»¸öÔªËصÄÀàÃûÓÐÁ½ÖÖÖ÷ÒªÒªÁ죺
1. ͨ¹ý getAttribute() ÒªÁì
´ËÒªÁì·µ»ØÖ¸¶¨ÔªËصÄÖ¸¶¨ÊôÐÔµÄÖµ¡£Òª»ñÈ¡ÀàµÄÊôÐÔ£¬¿ÉÒÔʹÓÃÒÔÏÂÓï·¨£º
element.getAttribute("class");
µÇ¼ºó¸´ÖÆ
ÀýÈ磺
<p id="my-paragraph" class="my-class">Hello world!</p>
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
const paragraph = document.getElementById("my-paragraph"); const className = paragraph.getAttribute("class"); console.log(className); // Êä³ö: "my-class"
µÇ¼ºó¸´ÖÆ
2. ͨ¹ý classList ÊôÐÔ
´ËÊôÐÔ·µ»ØÒ»¸ö DOMTokenList ¹¤¾ß£¬ÆäÖаüÀ¨ÔªËØÀàµÄÁÐ±í¡£¿ÉÒÔʹÓÃÒÔÏÂÓï·¨»á¼û¸ÃÊôÐÔ£º
element.classList;
µÇ¼ºó¸´ÖÆ
¸Ã¹¤¾ßÌṩÁ˼¸¸öÓÐÓõÄÒªÁ죬°üÀ¨£º
classList.add(className)£º½«Ò»¸öÐÂÀàÌí¼Óµ½ÔªËØ¡£
classList.remove(className)£º´ÓÔªËØÖÐɾ³ýÒ»¸öÀà¡£
classList.toggle(className)£ºÈôÊÇÔªËØûÓиÃÀ࣬ÔòÌí¼ÓËü£¬ÈôÊǸÃÔªËØÒÑÓµÓиÃÀ࣬Ôòɾ³ýËü¡£
classList.contains(className)£º¼ì²éÔªËØÊÇ·ñ¾ßÓÐÖ¸¶¨µÄÀà¡£
ÀýÈ磺
<p id="my-paragraph" class="my-class">Hello world!</p>
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
const paragraph = document.getElementById("my-paragraph"); const className = paragraph.classList; // Ìí¼ÓÒ»¸öÐÂÀà paragraph.classList.add("new-class"); // ´ÓÔªËØÖÐɾ³ýÒ»¸öÀà paragraph.classList.remove("my-class"); // ¼ì²éÔªËØÊÇ·ñ¾ßÓÐÖ¸¶¨µÄÀà if (paragraph.classList.contains("new-class")) { console.log("ÔªËؾßÓÐ 'new-class' Àà¡£"); }
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÔõô»ñÈ¡classÀàµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡