动态创建的HTML对象没有CSS应用到它

Dynamically Created HTML object not having CSS applied to it

本文关键字:CSS 应用 创建 HTML 对象 动态      更新时间:2023-09-26

最终产品:由word文档中的数据填充的Web页面,该文档被馈送到重复出现的HTML结构中。

问题:当运行时,创建了HTML元素,但是CSS类直到窗口调整大小才应用。

Javascrip:

    for (i=0; i<=timeline_data.length; i++){
        var newParent = document.getElementById('wgt-timeline-bdy-wrap-id');
        var newItem = document.createElement('div');
        newParent.appendChild(newItem);
        newItem.setAttribute('class','wgt-timeline-bdy-item');
        var newText = document.createElement('p');
        newItem.appendChild(newText);
        newText.setAttribute('class','timeline-new-text');
        newText.id="timeline-" + timeline_data[i].id + "-text";
    }
CSS:

.wgt-timeline-bdy-item {
    display: inline-block;
    font-size: 20px;
    position: relative;
    text-align: center;
    vertical-align: middle;
    width: 100%;
}
.timeline-new-text{
    font-size: 30px;
    position: relative;
    top:40px;
}

在HTML中没有什么意外的,wgt-timeline- body -wrap-id是一个div。

提前感谢您的帮助

尝试追加到DOM作为你在循环中做的最后一件事(即在你设置了类之后)。此外,大多数地方我都是通过element.className = 'xxx'而不是使用setAttribute()函数来完成的;不过我不确定这有什么关系。

尝试编写一个jQuery函数,以便在for循环执行完成后应用CSS样式。像这样:

for{...}
styleelements();
function styleelements(){
$(".wgt-timeline-bdy-item").css({...});
$(".timeline-new-text").css({...});
}