学习JavaScript
实战案例—便利贴
新人菜鸟一枚,记录日常学习前端知识
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
margin:0
}
button{
margin:20px 0;
}
main{
min-height: 550px;
background-color: rgb(182, 206, 243);
display: flex;
flex-wrap: wrap;
padding:10px;
}
.note{
margin: 10px;
width: 200px;
/* height: 200px; */
}
.note>div:nth-of-type(1){
background-color: orange;
line-height: 36px;
font-size: 30px;
display: flex;
justify-content: space-between;
padding: 0 10px;
}
.note>div:nth-of-type(1)>span:nth-of-type(1){
color: green;
}
.note>div:nth-of-type(1)>span:nth-of-type(2){
color: red;
}
.note>div:nth-of-type(2){
height: 170px;
background-color: white;
}
</style>
</head>
<body>
<button>添加便利贴</button>
<button>清空所有便利贴</button>
<main></main>
<!--便利贴放置的位置-->
<script>
var btns = document.querySelectorAll('button')
var main = document.querySelector('main')
// 创建一个便利贴
function addNote() {
var note = document.createElement('div')
note.className='note'
//创建note并添加class属性
var header = document.createElement('div')
var content = document.createElement('div')
//便利贴两部分,头部和可输入区域
content.contentEditable=true
// 允许用户进行输入,输入部分在div里,所以设置为可输入
var add = document.createElement('span')
add.innerHTML='+'
//便利贴头部的"+"符号
var remover = document.createElement('span')
remover.innerHTML='×'
//便利贴头部的"x"符号
header.appendChild(add)
//header头部添加add
header.appendChild(remover)
//header头部添加remover
note.appendChild(header)
//便利贴添加header头部
note.appendChild(content)
//便利贴添加输入区域
main.appendChild(note)
//将便利贴添加在main区域
add.onclick=function(){
addNote()
}
//add点击触发添加便利贴事件
remover.onclick=function(){
this.parentElement.parentElement.remove()
}
//remover点击触发移除便利贴事件,就是将父类的父类,即便利贴note移除
}
btns[0].onclick=function(){
addNote()
}
//添加便利贴按钮触发添加便利贴事件
btns[1].onclick=function(){
main.innerHTML=''
}
//清除全部便利贴
</script>
</body>
</html>
本案例的重点
- Javascript获取元素以及创建元素
- div标签设置可输入属性,contentEditable=true