我想创建几个元素,设置属性并将其放置在DOM,香草JS,在一个易于阅读的方式。
现在我在做它的方式是正常的功能做所有的DOM编辑,而是一个约束是,我需要跟踪当前元素,并添加它之前,我继续前进,创造下一个。
我刚开始学习班,并试图将想法转换成一类结构,但不能让它开始工作。
什么是这里的最佳做法?如果类可以做到这一点,什么是基本的代码来创建并追加一个div?
下面是我的代码(即工作),但我正在寻找改善逻辑
let body = document.querySelector("body");
// keeping track of the current div
let currentDiv;
// create and add attr
function createDiv(){
let newDiv = document.createElement("div");
currentDiv = newDiv;
}
function size(el, x, y){
el.style.height = y;
el.style.width = x;
}
function paintBG(el, clr){
el.style.backgroundColor = clr;
}
function append(parent){
parent.append(currentDiv);
}
// and then run the functions
createDiv();
size(currentDiv, "100%", "100px")
paintBG(currentDiv, "red");
append(body);
添加这些方法HTMLElement .Below是小例子。
let body = document.querySelector("body");
//create element with any tag like create('tagname')
function create(tag){
return document.createElement('div');
}
//append any number of child like body.append(elm1,elm2,elm3)
HTMLElement.prototype.append = function(...children){
children.forEach(child => {
this.appendChild(child);
})
return this;
}
//append the element to any other element
HTMLElement.prototype.appendTo = function(parent){
parent.appendChild(this);
return this;
}
//change the size
HTMLElement.prototype.size = function(x,y){
this.style.height = x;
this.style.width = y;
return this;
}
//changes color and background color
HTMLElement.prototype.paint = function(bgColor,textColor){
this.style.backgroundColor = bgColor;
if(textColor) this.style.color = textColor;
return this;
}
let myDiv = create('div').size('100px','100%').paint('blue','black').appendTo(body);
你是容易混淆的概念。
在DOM类是具有类似功能一起组项目,这样他们就可以进行查询/更新一批,以及以同样的方式称呼。
一个元素是一个元素,并且需要这样被创建。
一个<div class="header" />
和<span class="header" />
可以共享一个班,但他们将永远是不同的元素,因此,你不能“按类”动态地创建他们
在你的榜样寿,我建议使用CSS而不是单独操纵元素的样式。