Javascript:如何动态创建新的div,移动它,以各种方式修改它? [英] Javascript: How to create new div dynamically, change it, move it, modify it in every way possible?
问题描述
所以,我需要能够改变每个创建的div关于高度,宽度,上/左等。然而, document.getElementById(created_div)。style.whatever
什么都不做,我甚至不能看到一个新的div出现。我将新的divs height / width设置为500px,背景设置为red,依此类推,但是没有新的div显然出现。我究竟做错了什么?为什么这么难?啧。帮助!
- 创建
var div = document.createElement('div');
- 追加
document.body.appendChild(div) ;
- 风格操纵
- 定位
div.style.left ='32px';
div.style .top ='-16px';
- 类
div.className ='ui-modal';
- 定位
- 修改
- ID
div.id ='test';
- 内容(使用H TML)
div.innerHTML ='< span class =msg> Hello world。< / span>';
- 内容(使用文字)
div。 textContent ='Hello world。';
- ID
- 删除
div.parentNode.removeChild(div);
- 访问
- 按ID
div = document.getElementById('test');
- 按标签
array = document.getElementsByTagName('div');
- 按类
array = document .getElementsByClassName('ui-modal');
- 通过CSS选择器(单个)
div = document.querySelector('div #test .ui-modal' );
- CSS selector(multi)
array = document.querySelectorAll('div');
- 按ID
- 关系(包括文本节点)
- 关系(仅限HTML元素)
DOM操作的基础知识。请记住,新建节点在文档中是可见的,需要元素添加到正文或包含身体的节点。
I've been struggling with this for hours and I'm going insane. 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.
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. What am I doing wrong? Why is this so hard? Sheesh. Help!
- 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';
- Positioning
- Modification
- ID
div.id = 'test';
- contents (using HTML)
div.innerHTML = '<span class="msg">Hello world.</span>';
- contents (using text)
div.textContent = 'Hello world.';
- ID
- Removal
div.parentNode.removeChild(div);
- Accessing
- 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');
- by ID
- Relations (text nodes included)
- Relations (HTML elements only)
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屋!