簡體   English   中英

如何在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創建對象,該對象將動態創建具有樣式屬性的行,並將其附加到我的頁面。 我見過其他僅創建元素的解決方案,但沒有一個可以很好地適合單個對象。

這是我正在嘗試的代碼:

 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 ,但是沒有length屬性

要顯示,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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM