原生JS如何将div容器插入网页指定位置(如body顶部)
原生JS实现将创建的DOM元素插入到body顶部
appendChild()方法默认会将新节点添加到父节点的子节点列表末尾,这也是生成的div会出现在body最底部的原因。无需引入jQuery,原生JS提供了两种标准方案实现顶部插入:
方案1:使用insertBefore(全浏览器兼容)
insertBefore是DOM Level 1标准方法,无任何兼容问题,调用语法为父节点.insertBefore(新节点, 参照节点),新节点会被插入到参照节点的前一个位置。要将元素放到body最顶部,取body的第一个子节点作为参照节点即可。
将原代码中最后一行的document.body.appendChild(flipfinderContainer);替换为:
document.body.insertBefore(flipfinderContainer, document.body.firstChild);
特殊场景处理:如果执行插入时body还没有任何子节点,
document.body.firstChild会返回null,此时insertBefore的表现和appendChild完全一致,会直接将节点添加到body中,不会抛出异常。
方案2:使用prepend(写法更简洁)
所有现代浏览器(Chrome 54+、Firefox 49+、Safari 10+)均支持prepend方法,调用父节点.prepend(新节点)会直接将新节点添加到父节点的子节点列表最开头,写法更简洁:
document.body.prepend(flipfinderContainer);
Chrome扩展场景下脚本运行在Chrome环境中,可无顾虑使用该写法。
修改后的完整可运行代码
// Content-Script Function: This function toggles the extention on and fetches the required resources from the server. function toggleExtOn() { //Get url for the html page. let url = chrome.runtime.getURL("flipfinder.html"); //Create the container. var flipfinderContainer = document.createElement('div'); //Set the id. flipfinderContainer.setAttribute("id", "flipfinderContainer"); //Add the html to the div using iframe. flipfinderContainer.innerHTML = "<h1>Hello</h1>"; // 插入到body顶部 document.body.prepend(flipfinderContainer); // 如需兼容极老运行环境,替换为下一行代码即可 // document.body.insertBefore(flipfinderContainer, document.body.firstChild); }
内容的提问来源于stack exchange,提问作者Aeryes
相关产品推荐
相关产品推荐

