我如何在JavaScript中创建一个对象,它动态地创建一个div(带有样式属性和id)并追加到我的html页面



我试图在javascript中创建一个对象,该对象将动态创建具有样式属性的行,并将其附加到我的页面。我看到过其他的解决方案,只是创建一个元素,但没有一个可以很好地适应一个单一的对象。

这是我正在尝试的代码:

function line(pos_x, pos_y, length, width, color, num) {
	this = document.createElement('div');
    this.style.left = pos_x + "%";
	this.style.top = pos_y + "%";
	this.style.length = length + "%";
	this.style.width = width + "%";
	this.style.backgroundColor = color;
    this.id = "line" + num;
    document.appendChild(this);
}
var line1 = line(10, 0, 100, 100, #2ecc71, 1);

不要设置this

http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

也有style.width,但没有长度属性

div需要style.height > 0px

function line(pos_x, pos_y, thickness, width, color, num) {
	var line = document.createElement('div');
    line.style.left = pos_x + "%";
	line.style.top = pos_y + "%";
	line.style.height = thickness + "px";
	line.style.width = width + "%";
	line.style.backgroundColor = color;
    line.id = "line" + num;
    document.appendChild(line);
    return line;
}
var line1 = line(10, 0, 10, 100, #2ecc71, 1);

最新更新