JS——封装一个可以连缀的DOM库
2017-04-05 09:42
302 查看
function $(){ return new Base(); //每次要调用new一个新对象否则回造成叠加 } function Base(){ this.elements=[]; //因为要返回new对象所以创建一个数组保存获取的DOM对象 this.getId=function(id){ this.elements.push(document.getElementById(id)); return this; }; this.getTagName=function(tagName){ var tags = document.getElementsByTagName(tagName); for(var i = 0;i < tags.length;i++){ //getElementsByTagName获取的是数组要所以要遍历元素 this.elements.push(tags[i]); }; return this; }; this.getClass=function(className,n){ if(arguments.length==1){ //判断参数,如果1个参数是要获取所有Class var all = document.getElementsByTagName("*"); for(var i = 0;i<all.length;i++){ if (all[i].className==className){ this.elements.push(all[i]); } } }else if(arguments.length==2){ //两个参数是想获取第n个class this.elements.push(document.getElementsByClassName(className) ); } return this; }; } Base.prototype.addClass=function(className){ //添加class for(var i = 0;i < this.elements.length;i++){ this.elements[i].className += " " + className; } return this; } Base.prototype.css=function (attr,value){ for(var i = 0;i < this.elements.length;i++){ if(arguments.length==1){ //1个参数是要的到属性值 if(typeof window.getComputedStyle != "undefined"){ //判断浏览器是否支持getComputedStyle return window.getComputedStyle(this.elements[i],null).getPropertyValue(attr); }else if(typeof this.element[i].currentStyle != "undefined"){ //判断是否支持currentStyle return this.element[i].currentStyle.getAttribute(attr); } } this.elements[i].style[attr]=value; //如果不是1个参数设置属性并返回对象 }; return this; } Base.prototype.html=function (value){ //innerHTML方法 for(var i = 0;i < this.elements.length;i++){ if(arguments.length==0){ //如果没传参数表示要获取innerHTML return this.elements[i].innerHTML; } this.elements[i].innerHTML=value; //有参数是要设置innerHTML }; return this; } Base.prototype.click=function(fn){ //添加click方法 for (var i = 0;i < this.elements.length;i++){ this.elements[i].onclick=fn }; return this; }
这样就封装好了 一个 DOM相关方法;
每次这样调用:
$().getClass("box",1).css("backgroundColor","#ccc").innerHTML("直接获取了class名为box的第2个元素对象并设置了background-color为#ccc并设置标签内容为这段文字")
直接获取了class名为box的第2个元素对象并设置了background-color为#ccc并设置标签内容为这段文字,这样将很多DOM方法封装后 十分简便
相关文章推荐
- Vue.js插件axios——封装一个可以灵活使用的ajax
- 一个很好的javascript框架,prototype.js 1.4,很好的封装了ajax的应用。
- 一个AJAX自动完成功能的js封装源码[支持中文]第1/2页
- js可以利用dom非常轻松的就可以遍历一个表格。当然只要是dom中有的所有对象都可以通过js来访问和处理。
- 一个JS封装的GanttChart
- 封装了一个自动生成渐变字的JS类(clip)
- 一个可以在页面上随意画线、多边形、圆,填充等功能的js
- GreyFrame是一个遮罩弹出显示页面的JS类, 它可以允许你像在框架(如: frame和iframe)中打开一个链接.
- 一个封装了的选项卡效果js
- [c++]一个对MSXML的封装类 使用C++的Smart Pointer 对MSXML DOM封装,可以方便地访问xml文件
- JS_拖动_一个封装好的拖动层效果
- 一个全国地区的js文件,可以用于对省市地区的选择。
- 用js写的一个形式为##.dd的动态小数掩码问题,可以处理负值 NumberMask
- 前不久写的一个XMLHttpRequest封装类。加上了一个请求池,并可以添加多个事件监听器
- 一个封装的创建DOM元素的JS方法
- 刚刚找到的一个JS的应用代码大全,可以用来作技术资料查询
- [c++]一个对MSXML的封装类 使用C++的Smart Pointer 对MSXML DOM封装,可以方便地访问xml文件
- 一个封装的在后台弹出JS Alert消息和JS confirm信息以及跳转到指定的页面
- 本人写的一个不错的js封装类(有什么不好的地方请提出)
- 一个封装了的选项卡效果js