如何在JavaScript中动态创建新的div,更改它,移动它,以各种可能的方式修改它? [英] How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?
问题描述
我想在页面加载时创建新的div。这些div将显示为一个有序组,它根据JSON文件中的外部数据而变化。我需要使用for循环执行此操作,因为需要超过100个div。
I want to create new divs as the page loads. These divs will appear as an ordered group which changes depending upon external data from a JSON file. I will need to do this with a for loop because there are over 100 divs needed.
因此,我需要能够根据高度更改每个创建的div,宽度,顶部/左侧等。然而, document.getElementById(created_div)。style.whatever
什么都不做,我甚至看不到一个新的div出现。我将新div的高度/宽度设置为500px,背景设置为红色,依此类推,但没有新的div肯定会出现。
So, I need to be able to change each created div in regards to height, width, top/left and so on. Yet, document.getElementById("created_div").style.whatever
does nothing, I can't even see a single new div appear. I've set the new divs height/width to 500px, background to "red", and so on, but no new divs are definitely appearing.
我在做什么错误?
推荐答案
- 创建
var div = document.createElement('div');
- 添加
document.body.appendChild(div) ;
- 样式处理
- 定位
div.style.left ='32px';
div.style .top =' - 16px';
- 类
div.className ='ui-modal';
- Creation
var div = document.createElement('div');
- Addition
document.body.appendChild(div);
- Style manipulation
- Positioning
div.style.left = '32px';
div.style.top = '-16px';
- Classes
div.className = 'ui-modal';
- ID
div.id ='test';
- 内容(使用HTML)
div.innerHTML ='< span class =msg> Hello world。< / span>';
- 内容(使用文本)
div.textContent ='Hello world。';
- ID
div.id = 'test';
- contents (using HTML)
div.innerHTML = '<span class="msg">Hello world.</span>';
- contents (using text)
div.textContent = 'Hello world.';
- 由ID
div = document.getElementById('test');
- 按标签
array = document.getElementsByTagName('div');
- 按类
array = document.getElementsByClassName('ui-modal');
- 通过CSS选择器(单个)
div = document.querySelector( 'div #test .ui-modal');
- 由CSS选择器(多个)
array = document.querySelectorAll('div');
- by ID
div = document.getElementById('test');
- by tags
array = document.getElementsByTagName('div');
- by class
array = document.getElementsByClassName('ui-modal');
- by CSS selector (single)
div = document.querySelector('div #test .ui-modal');
- by CSS selector (multi)
array = document.querySelectorAll('div');
- children
node = div.childNodes[i];
- sibling
node = div.nextSibling;
- children
element = div.children[i];
- sibling
element = div.nextElementSibling;
这涵盖了DOM操作的基础知识。请记住,新创建的节点在文档中可见,需要向正文添加元素或包含主体的节点。
This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.
这篇关于如何在JavaScript中动态创建新的div,更改它,移动它,以各种可能的方式修改它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Positioning
- 定位