Teaching video https://space.bilibili.com/519965290?spm_id_from=..0.0
appendChild()/append() - 在被选元素的内部的结尾插入内容
prepend() - 在被选元素的内部的开头插入内容
after() - 在被选元素之后插入内容
before() - 在被选元素之前插入内容
(function() {
'use strict';
var bg=document.querySelector('.cos-pc'); //通过class获取body
var bt=document.createElement('button');
bt.innerHTML='一键更换背景';
bt.id='btn'; //设button的id
bg.prepend(bt); //在被选元素最前插入
var btn=document.querySelector('#btn'); //获取button
btn.style.fontSize='20px';
btn.style.position='absolute'; //把button改为浮动
btn.style.zIndex='999'; //在最上面添加一个覆盖器,防止被选元素覆盖之前显示的错误
// Your code here...
})();
Effect
Case: Baidu one-click skin change
(function() {
'use strict';
var bg=document.querySelector('.cos-pc');
var bt=document.createElement('button');
bt.innerHTML='一键更换背景';
bt.id='btn';
bg.prepend(bt); //在被选元素最前插入
var btn=document.querySelector('#btn'); //获取button
btn.style.fontSize='20px';
btn.style.position='absolute'; //把button改为浮动
btn.style.zIndex='999'; //在最上面添加一个覆盖器,防止被选元素覆盖之前显示的错误
var index=0; //定义一个变量来跟踪选中项的索引,初始为0,当选中项被
btn.addEventListener('click',function(){ //判断按钮是否按下
if(index!=0){
bg.style.backgroundColor= 'green'; //把背景变成绿色
index=0; //将选中项的索引设置为0 (假如按下了一个按钮,则索引变成0)
}
else{
bg.style.backgroundColor= ''; /\*清空背景颜色\*/
index=1; //假如按下了一个按钮,则索引变成1 (一个按钮只能选中一个项)
}
}); //listen for clicks on the button and execute the function associated with
// bg.style.backgroundColor="green";
// Your code here...
})();
Effect