js的封装库css

var $ = function () {
    return new Base();
}

function Base() {

    //创建一个数组,来保存获取的节点和节点数组
    this.elements = [];
    
    //获取ID节点
    this.getId = function (id) {
        this.elements.push(document.getElementById(id));
        return this;
    };
    
    //获取元素节点
    this.getTagName = function (tag) {
        var tags = document.getElementsByTagName(tag);
        for (var i = 0; i < tags.length; i ++) {
            this.elements.push(tags[i]);
        }
        return this;
    };
    
}


Base.prototype.css = function (attr, value) {
    for (var i = 0; i < this.elements.length; i ++) {
        this.elements[i].style[attr] = value;
    }
    return this;
}

Base.prototype.html = function (str) {
    for (var i = 0; i < this.elements.length; i ++) {
        this.elements[i].innerHTML = str;
    }
    return this;
}

Base.prototype.click = function (fn) {
    for (var i = 0; i < this.elements.length; i ++) {
        this.elements[i].onclick = fn;
    }
    return this;
}

引用的js如下

window.onload = function () {
    //alert(base.getId('box').elements.length);
    $().getId('box').css('color', 'red').css('backgroundColor', 'black');
    //alert(base.getTagName('p').elements.length);
    $().getTagName('p').css('color', 'green').html('标题').click(function () {
        alert('a');
    }).css('backgroundColor', 'pink');
};

html结构
<div id="box">box</div>

<p>01</p>
<p>02</p>
<p>03</p>

posted @ 2015-07-01 17:08  前行者在此  阅读(820)  评论(0编辑  收藏  举报