发布评论 (JavaScript交互特效案例 02)

展示

代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
      *{
        margin: 0;
        padding: 0;
      }
      ul{
        list-style: none;
      }
      #comment{
        width: 80%;
        padding: 10px 10px;
        font-size: 20px;
        outline: none;
      }
      #box{
        width: 1000px;
        border: 1px solid #ccc;
        margin: 100px auto;
        padding: 20px 20px;
      }
      .box_top{
        margin-bottom: 20px;
      }
      #comment_content li{
        border-bottom: 1px dashed #ccc;
        width: 800px;
        color: red;
        line-height: 45px;

      }
      #comment_content li a{
        float: right;
      }

    </style>
  </head>
  <body>
    <div id="box">
      <div class="box_top">
        <textarea  id="comment" cols="80" rows="10" placeholder="请输入你的评论"></textarea>
        <button id ="btn">发布</button>
      </div>
      <ul id="comment_content">
        <!-- <li>
        我的内容
        <a href="javascript:void(0);">删除</a>
      </li> -->
      </ul>
    </div>

  </body>
  <script type="text/javascript">
    window.onload = function(){

      btn = document.getElementById('btn');

      btn.onclick = function(){
        // console.log("点击")
        //
        var content = $('comment').value;

        if(content.length===0){
          alert('请输入内容');
          return;
        }
        var newli = document.createElement('li');
        newli.innerHTML =`${content}<a href="javascript:void(0)">删除</a>`;
        $('comment_content').appendChild(newli);
        $('comment').value = ""

        var delBtns = document.getElementsByTagName('a')
        // console.log(delBtns)
        for(var i = 0; i<delBtns.length;i++){
          delBtns[i].onclick = function(){
            this.parentNode.remove();
          }
        }


      };

      function $(id){
        return typeof id ==='string'? document.getElementById(id):null;
      }
    }
  </script>
</html>

猜你喜欢

转载自blog.csdn.net/PieroPc/article/details/131359580