简单的原生js 模拟jquery方法

仓促的模拟敲一下就上传来保存了。

Object.prototype.fadeIn = function(speed) {
var that = this;
setTimeout(function() {
that.style.display = "block"
}, speed)
return that;
}

//原生模拟jq中 fadeOut()方法;
Object.prototype.fadeOut = function(speed) {
var that = this;
setTimeout(function() {
that.style.display = "none"
}, speed)
return that;
}

//原生模拟jq中 hasClass()方法;
Object.prototype.hasClass = function(str) {
var obj = this;
if(str == "" || obj === null || obj.length === 0) {
return false;
}
if(obj.length > 1) {
return obj[0].classList.contains(str);
} else {
return obj.classList.contains(str);
}
}

//原生模拟jq中 addClass()方法;
Object.prototype.addClass = function(className) {
var obj = this;
if(className == "" || obj === null || obj.length === 0) {
return false;
}
if(obj.length > 1) {
[].forEach.call(obj, function(v, i) {
v.classList.add(className);
})
} else {
obj.classList.add(className);
}

return obj;
}

//原生模拟jq中 removeClass()方法;
Object.prototype.removeClass = function(className) {
var obj = this;
if(className == "" || obj === null || obj.length === 0) {
return false;
}
if(obj.length > 1) {
[].forEach.call(obj, function(v, i) {
v.classList.remove(className);
})
} else {
obj.classList.remove(className);
}

return obj;
}

//原生模拟jq中 $符号;
function $(str) {
if(typeof(str) !== "string" && (str === window || str === document)) {
return str;
}
if(str.trim() === "") {
return false;
}
if(str.trim().substr(0, 1) == "#") {
return document.getElementById(str.replace(/#/, ""));
} else {
return [].map.call(document.querySelectorAll(str), function(v, i) {
return v;
})
}
}

 

有什么差漏或不足,请指正下!

posted @ 2017-12-15 11:23  leehf  阅读(534)  评论(0编辑  收藏  举报