我有以下代码:
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
此代码按我的预期工作,在将动态元素附加到文档后,会出现一个 5 x 5 的蓝色框。当我尝试通过其 className 访问元素以进一步设置样式时,问题就开始了:
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
这段代码应该定位盒子,但它什么也没做,我做错了什么?最好我正在寻找一个纯 JS 解决方案,所以没有 JQuery。
提前致谢:)
最佳答案
问题
div 的属性 position 的默认值为 static。当您尝试在静态元素上设置左/右 [..] 时,它对该元素没有影响。
static : every element has a static position by default, so the element will stick to the normal page flow. So if there is a left/right/top/bottom/z-index set then there will be no effect on that element. relative : an element's original position remains in the flow of the document, just like the static value.
解决方案
- 您必须将创建元素中的位置属性设置为
absolute
、fixed
或relative
。
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.position = "absolute"
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
关于javascript - 无法将样式应用于 javascript 中动态创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65642167/