base层提供俩个职责,一是封装不同浏览器下javascript的差异,完成跨浏览器的工作;二是提供扩展javascript的底层接口,即提供函数便于上层调用。
职责一,提供的浏览器兼容的函数:
1)获取下一个兄弟节点的函数getNextNode
<script>
function getNextNode(node){
node = typeof node =="String"? getElementById(node): node;
var nextNode = node.nextSibling;
if(!nextNode) return null;
if(!document.all){
while(true){
if(nextNode.nodeType == 1){
break;
}else{
if(nextNode.nextSibling){
nextNode = nextNode.nextSibling;
}else{
break;
}
}
}
}
return nextNode;
}
</script>
2)获取事件的对象getEventTarget函数
<script>
function getEventTarget(e){
e= window.event || e;
return e.srcElement || e.target;
}
//使用
document.getElementByIdx_x_x_x_x_x_x_x("id").onclick = function(e){
var node = getEventTarget(e);
alert(node.tagName);
}
</script>
3) 阻止冒泡stopPropagation函数
<script>
function stopPropagation(e){
e = window.event || e;
if(document.all){
e.cancelBubble = true;
}else{
e.stopPropagation();
}
}
//使用
btn.onclick = function(e){
infoBox.innerHTML = "你点击的是:input";
stopPropagation(e);
}
</script>
职责二:提供更多的接口,即函数给上层调用
1)去除字符串首位空格字符函数trim():
<script>
function trim(ostr){
return ostr.replace(/^\s+|\s+$/g,"");
}
</script>
2)类型判断函数isNumber(),isString(),isBoolean(),isFunction(),isNull(),isUndefined(),isEmpty(),isArray():
<script>
function isNumber(s){
return !isNaN(s);
}
function isString(s){
return typeof s ==="string";
}
function isBoolean(s){
return typeof s ==="boolean";
}
function isFunction(s){
return typeof s ==="function";
}
function isNull(s){
return s === null;
}
function isUndefined(s){
return typeof s === "undefined";
}
function isEmpty(s){
return /^\s*$/.test(s);
}
function isArray(s){
return s instanceof Array;
}
</script>
3) getElementsByClassName(),函数接受三个参数,第一个参数是必选的,其它可选,第一个参数是class名,第二个参数是父容器,缺省是为body节点,第三个参数是DOM节点的标签名。
<script>
function getElementsByClassName(str,root,tag){
if(root){
root = typeof root =="string"? document.getElementByIdx_x_x_x_x_x(root):root;
}else{
root = document.body;
}
tag = tag || "*";
var els = root.getElementsByTagName_r(tag),arr=[];
for(var i=0,n=els.length; i<n; i++){
for(var j =0,k=els[i].split(" "),l=k.length; j<l; j++){
if(k[j]==str){
arr.push(els[i]);
break;
}
}
}
return arr;
}
</script>
4) extend继承函数,其原理是采用寄生组合继承
<script>
function extend(subClass,superClass){
var F = function(){};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if(superClass.prototype.constructor == Object.prototype.constructor){
superClass.prototype.constructor = superClass;
}
}
</script>