我如何在 JavaScript 中创建一个动态创建 div(具有样式属性和 ID)并附加到我的 html 页面的对象?
How do I create an object in JavaScript, that dynamically creates a div (with style properties and an id) and appends to my html page?
我正在尝试在 javascript 中创建一个对象,该对象将动态创建具有样式属性的行,并将其附加到我的页面。我见过其他仅创建一个元素的解决方案,但 none 可以很好地适合单个对象。
这是我正在尝试的代码:
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);
我正在尝试在 javascript 中创建一个对象,该对象将动态创建具有样式属性的行,并将其附加到我的页面。我见过其他仅创建一个元素的解决方案,但 none 可以很好地适合单个对象。
这是我正在尝试的代码:
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);