jsÔõô»ñÈ¡class
»ñÈ¡ javascript ÖÐÔªËØµÄ class ÓÐÁ½ÖÖÒªÁ죺ʹÓà element.classlist.value ÊôÐÔÖ±½Ó»ñÈ¡ class ÁбíµÄ×Ö·û´®£»Ê¹Óà element.getattribute(‘class’) ÒªÁì»ñÈ¡ class ÊôÐÔµÄÖµ¡£
ÔõÑùÔÚ JavaScript ÖлñÈ¡ÔªËØµÄ Class
ÒªÔÚ JavaScript ÖлñÈ¡ÔªËØµÄ class£¬¿ÉÒÔʹÓÃÒÔÏÂÁ½ÖÖÒªÁ죺
1. Element.classList.value
Element.classList.value ÊôÐÔ·µ»ØÔªËØµÄ class ÁбíµÄ×Ö·û´®¡£ÈôÊÇÔªËØûÓÐ class£¬Ôò·µ»ØÒ»¸ö¿Õ×Ö·û´®¡£
const element = document.querySelector('.my-element'); const classList = element.classList.value; console.log(classList); // Êä³ö£º"my-element"
µÇ¼ºó¸´ÖÆ
2. Element.getAttribute(‘class’)
Element.getAttribute(‘class’) ÒªÁì·µ»ØÔªËØµÄ class ÊôÐÔµÄÖµ¡£ÈôÊÇÔªËØûÓÐ class ÊôÐÔ£¬Ôò·µ»Ø null¡£
const element = document.querySelector('.my-element'); const classList = element.getAttribute('class'); console.log(classList); // Êä³ö£º"my-element"
µÇ¼ºó¸´ÖÆ
ÕâÁ½ÖÖÒªÁ춼¿ÉÒÔÓÃÀ´»ñÈ¡ÔªËØµÄ class£¬µ« classList ÊôÐÔ¸üÀû±ã£¬ÓÉÓÚËüÔÊÐíÄã²Ù×÷ÔªËØµÄ class ÁÐ±í¡£Äã¿ÉÒÔʹÓà classList.add(), classList.remove() ºÍ classList.toggle() À´Ìí¼Ó¡¢É¾³ýºÍÇл»ÔªËØµÄ class¡£
ÒÔÉϾÍÊÇjsÔõô»ñÈ¡classµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡