JavaScript案例之便利贴

学习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='&times;'
	  //便利贴头部的"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>

便利贴案例

本案例的重点

  1. Javascript获取元素以及创建元素
  2. div标签设置可输入属性,contentEditable=true
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值