
本文介绍了如何使用 JavaScript 在页面加载后动态创建和设置嵌套的 `div` 元素,包括创建 `
` 标签和 `
在 Web 开发中,有时需要在页面加载后动态地创建和添加 HTML 元素。例如,根据用户的操作或从服务器获取的数据,动态地生成内容。本文将介绍如何使用 JavaScript 动态创建和设置嵌套的 div 元素,并提供示例代码和注意事项。
动态创建元素并添加到 DOM
以下示例演示了如何使用 JavaScript 动态创建
标签和
首先,HTML 结构如下:
立即学习“Java免费学习笔记(深入)”;
对应的 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
<iframe src="https://www.php.cn/link/fe772ff1261b820e437821342b445539" id="syndicationPanelModalIFrame" width="100%" height="100% style="border: none;"`; newSyndicationModalContainer.style.display = 'block';}
代码解释:
newSyndicationModalContent.innerHTML =
Hello
newSyndicationModalContainer.style.display = ‘block’ 使容器可见。
动态修改元素的属性
除了创建元素之外,还可以动态修改元素的属性,例如 outerHTML、innerHTML 和 innerText。
let div = document.createElement("div");div.innerHTML = `Bla Bla Bla Blah`;div.style = "dispaly: grid";
代码解释:
div.innerHTML = Bla Bla Bla Blah`设置div` 元素的内部 HTML 内容。div.style = “dispaly: grid” 设置 div 元素的样式。
总结
本文介绍了使用 JavaScript 动态创建和设置嵌套 div 元素的几种方法,包括使用 document.createElement 和 innerHTML。同时,还讨论了如何动态修改元素的属性。在实际开发中,可以根据具体需求选择合适的方法。需要注意的是,使用 innerHTML 可能会带来安全风险,建议在可信的环境中使用。
以上就是使用 JavaScript 动态创建和设置嵌套 Div的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1596919.html
微信扫一扫
支付宝扫一扫