javascript - 无法将样式应用于 javascript 中动态创建的元素

标签 javascript html css

我有以下代码:

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.

解决方案

  • 您必须将创建元素中的位置属性设置为 absolutefixedrelative

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/

相关文章:

javascript - 替换整个页面上多个单词的所有实例

javascript - Codeigniter 和 AJAX - 关闭编辑模式时重置/清除模式表单

javascript - React hooks 将引用存储到第三方库的最佳实践

javascript - jQuery .text() 显示双文本

javascript - 如何保证一些内容总是堆叠在主要内容的后面

javascript - 简单的 jQuery 动画不起作用

jquery - 如何将DIV内容发送到html5 CANVAS

css - 使用css表格显示div

html - webkit 浏览器上的 CSS - 元素有时定位不正确

css - 如何将angular-7中的 "%"中的 "Point"更改为 "ng-circle-progress"?