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

来源:互联网 发布:小说软件破解版 编辑:程序博客网 时间:2024/06/05 02:06
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="index01.js"></script>
<script src="index02.js"></script>
</head>


<body>
<div id="clas">ddd</div>
<div id="ff" style="display:none">fff</div>
<p>我是p1</p>
<p>我是p2</p>
<input type="tel" name="tel" />
</body>

</html>


//这里调用

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<targs.length;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;i<this.elements.length;i++){
if(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;i<this.elements.length;i++){
if(arguments.length==0){
return this.elements[i].innerHTML
}
this.elements[i].innerHTML = str;
}
return this;
}
//增加点击事件
Base.prototype.click = function(fn){ //给函数体添加方法 用原型
for(var i=0;i<this.elements.length;i++){
this.elements[i].onclick = fn;
}
return this;
}
//增加hover事件
Base.prototype.hover = function(over,out){ 
for(var i=0;i<this.elements.length;i++){
this.elements[i].onmouseover = over;
this.elements[i].onmouseout = out;
}
return this;
}


//设置显示 
Base.prototype.show = function(){
for(var i=0;i<this.elements.length;i++){
this.elements[i].style.display = 'block'; 
}
return this;
}
//设置隐藏
Base.prototype.hide = function(){
for(var i=0;i<this.elements.length;i++){
this.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;i<this.elements.length;i++){
this.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;
}

1 0