js中用对象的方式操作dom

 

xuhaitao = {};
xuhaitao.ele = function(dom) {
    this.dom = dom;
}

xuhaitao.ele.prototype = {
        setId(id) {
            this.dom.id = id;
        },
        setClass(namee) {
            this.dom.className = namee;
        },
        setStyle(key, val) {
            this.dom.style[key] = val;
        },
        setContent(val) {
            this.dom.innerText = val;
        }
    }
    //设置样式另一种方式
var props = ["display", "marginLeft", "marginTop", "color", "backgroundColor", "height"];
props.forEach(function(pr) {
    var method = 'set' + pr.substr(0, 1).toUpperCase() + pr.substr(1, pr.length);
    xuhaitao.ele.prototype[method] = function() {
        this.setStyle(pr, arguments[0]);
        return this;
    };
});

var domm = document.getElementsByTagName("p");
var ele01 = new xuhaitao.ele(domm[0]);
ele01.setId("id01");
ele01.setClass("tian");

ele01.setStyle("width", "500px");
ele01.setContent("hunkxu");
ele01.setColor("red");
ele01.setMarginLeft("100px");
ele01.setMarginTop("100px");
ele01.setBackgroundColor("yellow");
ele01.setHeight("500px");


版权声明:本文为qq_15267341原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。