I'm trying to create an object in javascript that will dynamically create a line with style properties, and attach it to my page. I've seen other solutions that just create an element, but none that can be nicely fit into a single object.
我正在尝试在javascript中创建一个对象,它将动态创建一个带有样式属性的行,并将其附加到我的页面。我见过其他解决方案只是创建一个元素,但没有一个可以很好地适合单个对象。
Here's the code I'm trying:
这是我正在尝试的代码:
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);
1 个解决方案
#1
0
Don't set this
不要设置它
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
Also, there is style.width
, but no length property
此外,还有style.width,但没有length属性
To be visible, the div needs style.height > 0px
要显示,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);
#1
0
Don't set this
不要设置它
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
Also, there is style.width
, but no length property
此外,还有style.width,但没有length属性
To be visible, the div needs style.height > 0px
要显示,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);