JavaScript使用链式方法封装jQuery中CSS()方法示例

2019-11-22,,,,,,

本文实例讲述了JavaScript使用链式方法封装jQuery中CSS()方法。分享给大家供大家参考,具体如下:

主要思路就是:返回this对象,将所获取的操作元素放入一个数组中。在原型中添加拓展方法

<html>
<head>
  <title></title>
</head>
<body>
  <div id="one">aa</div>
</body>
<script type="text/javascript">
//封装类似于JQuery的连缀
/*
思路:一个操作后再返回本来的对象this,将获取的元素放入一个数组内部。通过原型添加方法;
为了能在原型对象中添加方法;这个应该用函数来建立原型对象
function Base(){
  this.getId=function(id){
    return this;
  }
  使用的时候,需要new一个实例对象
  var newBase=Base();
}
*/
function Base(){
  this.element=[];
  //获取ID
  this.getId=function(id){
    //将所获取的元素放入数组里面,返回当前对象
      this.element.push(document.getElementById(id))
      // return this.element.length
      return this
    }
    //获取className,遍历push
    this.getClass=function(name){
      var names=document.getElementsByName(name);
      for( var i=0;i<names.length;i++){
        this.element.push(names[i])
      }
      return this;
    }
    //获取tagName;遍历push
    this.getTag=function(tags){
      var tags=document.getElementsByTagName(tags);
      for(var i=0;i<tags.length;i++){
        this.element.push(tags[i])
      }
      return this;
    }
  }
//通过原型添加方法:
Base.prototype.css=function(attr,value){
  //遍历选取当前元素
  for(var i=0;i<this.element.length;i++){
    this.element[i].style[attr]=value;
  }
  return this;
}
var newBase= new Base();
// alert(newBase.getId("one"))
newBase.getId("one").css("background","red").css("color","blue").css("fontSize","60")
</script>
</html>

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript页面元素操作技巧总结》、《JavaScript事件相关操作与技巧大全》、《JavaScript操作DOM技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》

希望本文所述对大家JavaScript程序设计有所帮助。

您可能感兴趣的文章:

  • 让JavaScript中setTimeout支持链式操作的方法
  • JS链式调用的实现方法
  • JavaScript 对象链式操作测试代码
  • 原生js实现对Ajax的封装(仿jquery)
  • 原生js仿jquery实现对Ajax的封装
  • 原生js封装的一些jquery方法(详解)
  • 浅析jQuery Ajax通用js封装
  • 把jQuery的类、插件封装成seajs的模块的方法
  • 基于jquery封装的一个js分页
  • JS简单实现获取元素的封装操作示例
  • Javascript 详解封装from表单数据为json串进行ajax提交
  • JS简单封装的图片无缝滚动效果示例【测试可用】

《JavaScript使用链式方法封装jQuery中CSS()方法示例.doc》

下载本文的Word格式文档,以方便收藏与打印。