This method is implemented by the method of array and string, and can not meet the practical application, but only for learning ~ ~ ~
The characteristics of this method:
- Support for class additions without class nodes
- Support for adding nodes that already have a single or multiple class
- Mask already has a duplicate class for the node that wants to be with classname
- Adding multiple classes at once is not supported temporarily
- Remove class to support a single class node removal
- Remove class supports multiple class nodes to remove a single class
- Temporarily unable to "perfect" support removing multiple classes at once
The following is the source code:
1 <!DOCTYPE HTML>2 <HTMLxmlns= "http://www.w3.org/1999/xhtml">3 <Head>4 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" />5 <title>AddClass</title>6 <Script>7 window.onload= function () {8 9 Ten functionaddclass (obj, className) { One if(Obj.classname=== "') { A Obj.classname=ClassName; - } Else { - //if the class that you want to add does not exist in the original class the varArrclassname=Obj.className.split (' '); - if(Arrindexof (Arrclassname, ClassName)=== -1) { - Obj.classname+= ' ' +ClassName; - } + //if the class you want to add exists in the original class, do not manipulate the - + } A } at - functionremoveclass (obj, className) { - //First judge if obj has classname - if(Obj.classname!= "') { - varArrclassname=Obj.className.split (' '); - varClassindex=Arrindexof (Arrclassname, className); in if(Classindex!==-1) { - Arrclassname.splice (Classindex,1); to Obj.classname=Arrclassname.join (' '); + } - } the } * $ functionArrindexof (arr, v) {Panax Notoginseng for (varI= 0; I<arr.length; I++) { - if(Arr[i]==v) { the returni; + } A } the return -1; + } - $ functionOutputclassname (infocon,info) { $ infocon.innerhtml=info; - } - the varOdiv=document.getElementById ('Div1'); - varMText=document.getElementById ('Text1');Wuyi varMBTN1=document.getElementById ('BTN1'); the varmBtn2=document.getElementById ('btn2'); - Wu Mbtn1.onclick= function() { - addclass (Odiv, mtext.value); About outputclassname (Odiv, odiv.classname); $ }; - Mbtn2.onclick= function () { - removeclass (Odiv, mtext.value); - outputclassname (Odiv, odiv.classname); A }; + } the </Script> - </Head> $ <Body> the <inputID= "Text1"type= "text"value= "Newclass"/><inputID= "BTN1"value= "Add class"type= "button"/><inputID= "BTN2"value= "Removeclass"type= "button"/> the <P>ClassName of the target element: (temporarily adding more than one classname is not supported)</P> the <DivID= "Div1"></Div> the - in </Body> the </HTML>
Original articles, reproduced please indicate the source: http://www.eyezip.com/?p=992
Simple implementation of adding and removing Class,addclass/removeclass