【1】Add listening events
The code copy is as follows:
addHandler:function(node,type,fn){if(node.addEventListener){
node.addEventListener(type,fn,false); // false, set to bubble event
}
else{
node.attachEvent('on'+type,function(){
fn.apply(node,arguments); // In the attachEvent method, this does not point to node, so it needs to be changed by using the apply() method.
});
}
}
【2】Set the style of the element
The code copy is as follows:
setCss:function(node,val){ // val:{'top':'2px','font-size':'12px'}
for(var v in val){
node.style.cssText += ';'+ v +':'+val[v]; //Use cssText to set multiple attributes at the same time, and there is also an advantage that can avoid the judgment of cssFloat and styleFloat
}
}
【Three】Get the CSS class name element
The code copy is as follows:
//parent is an optional parameter.
getByClassName:function(className,parent){
var elem = [],
node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
p = new RegExp("(^|//s)"+className+"(//s|$)");
for(var n=0,i=node.length;n<i;n++){
if(p.test(node[n].className)){
elem.push(node[n]);
}
}
return elem;
}
【Four】Delete CSS class name
The code copy is as follows:
removeClassName:function(node,className){
var par = new RegExp(className,'g');
node.className = node.className.replace(par,'');
}
The above 4 are the native js functions that I have compiled and need to be used frequently. I recommend them to my friends, I hope they will be helpful to everyone.