1:我们将字符串进行封装:字符串不能绑定事件
2:将字符串变换成DOM元素
3:提取公用的类,如果想渲染DOM,可以通过setState
4:模拟实现了一个渲染的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>switch</title>
<style>
.switch{
/*去掉浏览器默认渲染*/
-webkit-appearance: none;
width: 50px;
height:32px;
border:1px solid #dfdfdf;
border-radius: 30px;
position: relative;
outline: none;
transition: linear 0.2s;
}
/*伪类*/
.switch:before{
content: '';
width: 30px;
height: 30px;
border-radius: 50%;
background: #ffffff;
position: absolute;
top: 0;
left: 0;
/*左右,上下,模糊距离,阴影大小,颜色*/
box-shadow: 1px 1px 4px 1px #dfdfdf;
transition: linear 0.2s;
}
.switch:checked{
box-shadow: 0 0 16px 16px #343cff inset;
transition: linear 0.2s;
}
.switch:checked:before{
/*right: 0;不会起作用*/
left: 20px;
/*上面不写left=0的时候动画不会起作用*/
transition: linear 0.2s;
}
</style>
</head>
<body>
<div class="app">
<input type="checkbox" class="switch">
<p class="text">关</p>
</div>
<script>
let btn=document.querySelector('.switch')
let text=document.querySelector('.text')
btn.addEventListener('change',function (e) {
console.log(e)
text.innerHTML=e.target.checked?'开':'关'
},false)
</script>
</body>
</html>
事件原e:
<!--第2份初稿;-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>switch</title>
<style>
.switch {
/*去掉浏览器默认渲染*/
-webkit-appearance: none;
width: 50px;
height: 32px;
border: 1px solid #dfdfdf;
border-radius: 30px;
position: relative;
outline: none;
transition: linear 0.2s;
}
/*伪类*/
.switch:before {
content: '';
width: 30px;
height: 30px;
border-radius: 50%;
background: #ffffff;
position: absolute;
top: 0;
left: 0;
/*左右,上下,模糊距离,阴影大小,颜色*/
box-shadow: 1px 1px 4px 1px #dfdfdf;
transition: linear 0.2s;
}
.switch:checked {
box-shadow: 0 0 16px 16px #343cff inset;
transition: linear 0.2s;
}
.switch:checked:before {
/*right: 0;不会起作用*/
left: 20px;
/*上面不写left=0的时候动画不会起作用*/
transition: linear 0.2s;
}
</style>
</head>
<body>
<div class="app">
</div>
<script>
// 步骤一:
// 1:我们将字符串进行封装以后,字符串不能绑定事件
// 2:将字符串变换成DOM元素
// class Switch {
// render() {
// return `
// <div>
// <input type="checkbox" class="switch">
// <p class="text">关</p>
// </div>
// `
// }
//
// }
// let app = document.querySelector('.app')
// app.innerHTML=new Switch().render()
// 步骤二
class Switch {
createDOMFromString(str){
let oDiv=document.createElement('div')
oDiv.innerHTML=str
return oDiv.firstElementChild;
}
// change(){
//
// }
render() {
this.el=this.createDOMFromString(`<div>
<input type="checkbox" class="switch">
<p class="text">关</p>
</div>`)
this.el.firstElementChild.addEventListener('change', (e)=> {
console.log(this.el)
console.log(this)
},false)
return this.el
}
}
let app = document.querySelector('.app')
app.appendChild(new Switch().render())
app.appendChild(new Switch().render())
</script>
</body>
</html>