在某元素后插入元素
- 我们这一次在按钮元素后面复制一个一模一样的按钮,所以分为几个步骤,先新建一个一样的元素,然后把相同中的属性赋值给它,再插入到合适的位置,最后再稍微修改一下外观样式即可
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/dbe9fadc308d7d814af91b73bdc3eb33.png)
- 首先新建一个input元素,看一下效果
window.onload=function(){
var theElement=document.createElement("input");
theElement.className="btn self-btn bg s_btn";
theElement.style="font-size: 17px";
theElement.id="theElement";
theElement.value="爱我中华";
theElement.type="submit";
theElement.onclick = function(){
alert("我爱中华");
}
document.querySelector("input[type=submit]").parentNode.append(theElement);
}
- 可以看到当我们新建一个一样的元素的时候,元素是一模一样的,只是位置有点不同
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fa35cc503eb353021a9d25509eb61178.png)
- 然后我们把样式再稍微调整一下父元素的排列组合样式让它们并排成为一行,并修改修按钮的右上角和右下角为直角即可
window.onload=function(){
var theElement=document.createElement("input");
theElement.className="btn self-btn bg s_btn";
theElement.style="font-size: 17px";
theElement.id="theElement";
theElement.value=" 爱我中华 ";
theElement.type="submit";
theElement.onclick = function(){
alert("我爱中华");
}
document.querySelector("input[type=submit]").parentNode.append(theElement);
document.querySelector("input[type=submit]").style="border-radius:0;";
theElement.parentNode.style.display="inline-flex";
}
- 再看一下效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ae8ad873bb36ee7b67a20fd69b044d18.png)
- 好了这里在固定位添加元素讲完了,先说一下
document.createElement()
是一个添加元素的函数,后面填的是什么就创建什么元素,然后返回值用一个var theElement
来储存,然后给theElement元素定义className
CSS共通样式,个别样式style
,并定义id
方便访问,value
用于定义显示的内容,type
用于定义这个input的类型,这里也可以用button
- 然后这种
theElement.onclick = function(){XXX}
这种格式就是给这个元素添加一个点击事件 append
是在子元素的最后再添加一个元素,所以这个被添加的元素如果是最后一个元素就刚好可以使用parentNode
往上溯源一代使用append
添加
在末尾插入自定义元素
window.onload=function(){
var theElement=document.createElement("div");
theElement.innerHTML='<div style="width:400px;height:100px;border:1px solid black;background:white;position:fixed;left:350px;bottom:150px;z-index:1500;"><p id="showtext" style="color:black">祖国万岁</p></div>';
document.body.append(theElement);
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/97a3d963fb5aae282eb4c4b497195e9f.png)
- 这里就是直接在
body
父元素中最后添加一个子元素 - 然后直接编辑这个元素的
innerHTML
,直接在里面添加所有想要添加的HTML代码即可,非常地方便,需要注意的就是里面全被视为一个字符串,所以外面本身就自带了引号'
,然后和里面的双引号"
要区分开. position:fixed
自由排列这个元素的位置left:350px;
离左边350像素bottom:150px;
离底150像素z-index:1500;
Z轴高度1500 在其它元素的顶层显示,然当如果还有其它更高层的元素我们可以把这个值调成更高