最近迷上了原生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自帶,省略。
新聞熱點
疑難解答
圖片精選