外观模式:为一组复杂的子系统接口提供一个更高级的统一接口,通过这个接口使得对子系统接口的访问更容易,在javaScript中用于对底层结构兼容性做统一封装来简化用户使用
兼容性优化:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| function addEvent(dom,type,fn){ if(dom.addEventListener){ dom.addEventListener(type,fn,false); }else if(dom.attachEvent){ dom.attachEvent('on'+type,fn) }else{ dom['on'+type]=fn } }
var getEvent=function(event){ return event||window.event }
var getTarget=function(event){ var event=getEvent(event) return event.target||event.srcElement
}
var preventDefault=function(event){ var event=getEvent(event) if(event.preventDefault){ event.preventDefault() }else{ event.returnValue=false; } };
addEvent(myInput,'click',function(e){ preventDefault(e) if(getTarget(e)!==document.getElementById('myInput')){ hideInputSug() } })
|
对接口方法的外层包装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var A={ g:function(id){ return document.getElementById(id) }, css:function(id,key,value){ document.getElementById(id).style[key]=value }, attr:function(id,key,value){ document.getElementById(id)[key]=value }, html:function(){ document.getElementById(id).innerHTML=html }, on:function(){ document.getElementById(id)['on'+type]=fn } } A.css('box','background','red') A.attr('box','className','box') A.html('box','这是新添加的内容')
|