自己用js封装的一些简单效果





无标题文档






ddd


我是p1


我是p2





//这里调用

window.onload = function(){
/*console.log($().getId('clas'));
console.log($().getTagName('p'));
console.log($().getName('tel'));
$().getTagName('p').css('color','red').html('我改变了').click(function(){
 alert(1);
});*/
//console.log($().getId('clas').html());
$().getId('clas').hover(function(){
$().getId('ff').show();
},function(){
$().getId('ff').hide();
});;
}


// JavaScript Document 封装的方法
function $(){
return new Base();
}
function Base(){
this.elements = [];
this.getId = function(id){
this.elements.push(document.getElementById(id));
return this;
};
this.getTagName = function(tag){
var targs = document.getElementsByTagName(tag);
 for(var i=0;i this.elements.push(targs[i]);
  }
 return this; //返回Base对象  
};
this.getName = function(name){
this.elements.push(document.getElementsByName(name));
return this;
}
}
Base.prototype.css = function(attr,value){
for(var i=0;iif(arguments.length ==1){
return this.elements[i].style[attr]; //获取html的值
}
this.elements[i].style[attr] = value;
}
return this;
};
//获取元素内容
Base.prototype.html = function(str){ 
for(var i=0;iif(arguments.length==0){
return this.elements[i].innerHTML
}
this.elements[i].innerHTML = str;
}
return this;
}
//增加点击事件
Base.prototype.click = function(fn){ //给函数体添加方法 用原型
for(var i=0;ithis.elements[i].onclick = fn;
}
return this;
}
//增加hover事件
Base.prototype.hover = function(over,out){ 
for(var i=0;ithis.elements[i].onmouseover = over;
this.elements[i].onmouseout = out;
}
return this;
}


//设置显示 
Base.prototype.show = function(){
for(var i=0;ithis.elements[i].style.display = 'block'; 
}
return this;
}
//设置隐藏
Base.prototype.hide = function(){
for(var i=0;ithis.elements[i].style.display = 'none'; 
}
return this;
}


//设置物体居中 
Base.prototype.center = function(width,height){
var top = (document.documentElement.clientHeight-width)/2;
var left = (document.documentElement.clientWidth-height)/2;
for(var i=0;ithis.elements[i].style.top = top+'px'; 
this.elements[i].style.left = left+'px'; 
}
return this;
}
//触发浏览器 移动时候 弹出层居中
Base.prototype.resize = function(fn){
window.onresize = fn;
return this;
}

你可能感兴趣的:(前端开发,封装)