首页 > 语言 > JavaScript > 正文

原生js仿jquery一些常用方法(必看篇)

2024-05-06 15:09:31
字体:
来源:转载
供稿:网友

最近迷上了原生js,能不用jquery等框架的情况都会手写一些js方法,记得刚接触前端的时候为了选择器而使用jquery。。。现在利用扩展原型的方法实现一些jquery函数:

1.显示/隐藏

//hide() Object.prototype.hide = function(){  this.style.display="none";  return this; } //show() Object.prototype.show = function(){  this.style.display="block";  return this; } 

return this的好处在于链式调用。

2.滑动 省略speed和callback的传入,因为要加一串判断和处理回调,代码量大

//slideDown() Object.prototype.slideDown = function(){  this.style.display = 'block';  if(this.clientHeight<this.scrollHeight){   this.style.height=10+this.clientHeight+"px";   var _this = this;   setTimeout(function(){_this.slideDown()},10)  }else{   this.style.height=this.scrollHeight+"px";  } } //slideUp() Object.prototype.slideUp = function(){  if(this.clientHeight>0){   this.style.height=this.clientHeight-10+"px";   var _this = this;   setTimeout(function(){_this.slideUp()},10)  }else{   this.style.height=0;   this.style.display = 'none';  } } 

3.捕获/设置

//attr() Object.prototype.attr = function(){  if(arguments.length==1){   return eval("this."+arguments[0]);  }else if(arguments.length==2){   eval("this."+arguments[0]+"="+arguments[1]);   return this;  } } //val() Object.prototype.val = function(){  if(arguments.length==0){   return this.value;  }else if(arguments.length==1){   this.value = arguments[0];   return this;  } } //html() Object.prototype.html = function(){  if(arguments.length==0){   return this.innerHTML;  }else if(arguments.length==1){   this.innerHTML = arguments[0];   return this;  } } //text()需要在html()结果基础上排除标签,会很长,省略 

4.CSS方法

 

//css() Object.prototype.css = function(){  if(arguments.length==1){   return eval("this.style."+arguments[0]);  }else if(arguments.length==2){   eval("this.style."+arguments[0]+"='"+arguments[1]+"'");   return this;  } } 

 5.添加元素

//append() Object.prototype.append = function(newElem){  this.innerHTML += newElem;  return this; } //prepend() Object.prototype.prepend = function(newElem){  this.innerHTML = arguments[0] + this.innerHTML;  return this; } //after() Object.prototype.after = function(newElem){  this.outerHTML += arguments[0];  return this; } //before() Object.prototype.before = function(newElem){  this.outerHTML = arguments[0] + this.outerHTML;  return this; } 

6.删除/替换元素

//empty() Object.prototype.empty = function(){  this.innerHTML = "";  return this; } //replaceWith() Object.prototype.replaceWith = function(newElem){  this.outerHTML = arguments[0];  return this; } //remove() js自带,省略。 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选