我正在尝试在网页加载时使用 JavaScript 更新 CSS 布局。我的代码如下所示:
var container = 0; // Add Total UI
var containerTitle = 0; // Container Title
var article = 0;
var articleTitle = 0;
var divName = 0; // temp variable for article id names
var divNameT = 0; // temp variable for title id names
function setLayout(id) {
container = document.getElementById(id);
for(var x = 0; x < 18; ++x) {
// CREATE CONTAINER FOR ALL PANELS
divName = "articleCon"+ x;
article = document.createElement('div');
article.id = divName;
// SETUP CSS STYLE
article.style.cssText = 'height: 205px; width: 300px; background: red; margin-right: 20px; margin-bottom: 20px; display: block; float: left;';
setNewsTitle(count,divName); // Function Call to set Title Panel
container.appendChild(article);
}
}
function setNewsTitle(count,id) {
containerTitle = document.getElementById(id);
// CREATE CONTAINER FOR TITLE
divNameT = "articleTitle"+ count;
articleTitle = document.createElement('div');
articleTitle.id = divNameT;
// SETUP CSS STYLE
articleTitle.style.cssText = 'position: absolute; height: 45px; width: 100px; background: yellow; display: inline;';
containerTitle.appendChild(articleTitle);
}
当我在不调用function setNewsTitle(count,id) 的情况下编译我的代码时,所有 CSS 元素都工作正常。 我在这里面临的问题是每当进行函数调用时,我的页面都会显示为空白。屏幕上没有任何显示。
我尝试添加屏幕截图以便更好地理解,但我还没有声誉。
最佳答案
尝试...
container.appendChild(article);
setNewsTitle(x,divName); // Function Call to set Title Panel
文章需要在 setNewsTitle
运行之前就位,因为您正在按 id 查找元素。另外,你没有count
,你有x
...
关于javascript - 使用 JavaScript 创建和附加嵌套的 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27785786/