本文介绍了如何使用 JavaScript 在页面加载后动态创建和设置嵌套的 `div` 元素,包括创建 `
` 标签和 `
在 Web 开发中,有时需要在页面加载后动态地创建和添加 HTML 元素。例如,根据用户的操作或从服务器获取的数据,动态地生成内容。本文将介绍如何使用 JavaScript 动态创建和设置嵌套的 div 元素,并提供示例代码和注意事项。
动态创建元素并添加到 DOM
以下示例演示了如何使用 JavaScript 动态创建
标签和
首先,HTML 结构如下:
对应的 CSS 样式如下:
.newSyndicationModalContainer {
display: none;
position: fixed;
z-index: 9999;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
.newSyndicationModalContent {
background-color: transparent;
margin: auto;
width: 100%;
height: 100%;
}JavaScript 代码如下:
const newSyndicationModalContainer = document.querySelector(".newSyndicationModalContainer");
const newSyndicationModalContent = document.querySelector(".newSyndicationModalContent");
if (newSyndicationModalContainer != undefined) {
var p = document.createElement('p');
p.innerText = "Hello!";
var iframe = document.createElement('iframe');
iframe.id = "syndicationPanelModalIFrame";
iframe.src = "http://sample.com";
iframe.width = "100%";
iframe.height = "100%";
iframe.style.border = "none";
newSyndicationModalContent.append(p, iframe);
newSyndicationModalContainer.style.display = 'block';
}代码解释:
- document.querySelector 用于获取具有指定 class 的 HTML 元素。
- document.createElement 用于创建新的 HTML 元素,例如
和
- 通过设置元素的属性(例如 innerText、src、width、height 和 style),可以自定义元素的外观和行为。
- newSyndicationModalContent.append(p, iframe) 将创建的
和
- newSyndicationModalContainer.style.display = 'block' 使容器可见。
使用 innerHTML 动态创建元素
另一种方法是使用 innerHTML 属性来动态创建元素。虽然这种方法比较简单,但它可能会带来一些安全风险,例如 XSS 攻击。因此,建议在可信的环境中使用 innerHTML。
const newSyndicationModalContainer = document.querySelector(".newSyndicationModalContainer")
const newSyndicationModalContent = document.querySelector(".newSyndicationModalContent")
if (newSyndicationModalContainer != undefined) {
newSyndicationModalContent.innerHTML = `Hello

.newSyndicationModalContent {
background-color: transparent;
margin: auto;
width: 100%;
height: 100%;
}






