<!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> .container { width: 1000px; margin: auto; } dd { background: #eee; margin-bottom: 20px; } .cover { position: fixed; left: 0; right: 0; top: 0; bottom: 0; background-color: rgba(0, 0, 0, .5); display: none; } .dialog { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); padding: 30px; background-color: #fff; } .show { display: block !important; } </style> </head> <body> <div class="container"> <h2>留言板</h2> <p> 昵称: <input type="text" class="nickname"> </p> <p> 留言: <textarea class="msg"></textarea> </p> <p> <button class="btn">留言</button> </p> <dl> <dt>大家都在说</dt> </dl> </div> <!-- 弹窗 --> <div class="cover"> <div class="dialog"> <h3>回复留言</h3> <textarea class="reply_msg"></textarea> <br> <button class="confirm_btn">确认回复</button> <button class="cancel_btn">取消回复</button> </div> </div> <script> // var oReply// !!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 事件委托:委托给谁? // document.addEventListener('click' , function(){}) document.onclick = function (e) { var e = e || event; var target = e.target || e.srcElement; // 留言 if (target.className === 'btn') { // 获取用户名和留言内容 var nickname = $('.nickname').value; var msg = $('.msg').value; if (nickname && msg) { // 创建留言 createMsg(nickname, msg) } } // 删除 if (target.className === 'del_btn') { target.parentNode.remove() } // 回复 if (target.className === 'reply_btn') { // 显示弹窗 // $('.cover').style.display = 'block' // className classList 区分使用!!!!!!!!!!!!!! // $('.cover').className.add() 错误的 // $('.cover').className += ' show'; $('.cover').classList.add('show'); // 找到回复留言的地方 // this和target的区别!!!!!!!!!!!!!!!!! oReply = target.previousElementSibling; console.log(oReply); } // 确认回复?????????????????????????????????????????????????? if (target.className === 'confirm_btn') { // 1 获取输入框的值 // 2 创建回复 // 3 关闭弹窗 var replyMsg = $('.reply_msg').value; if (replyMsg) { console.log(oReply); createReply(replyMsg); } } // 取消回复 if (target.className === 'cancel_btn') { $('.cover').classList.remove('show'); } } // 创建回复 function createReply(msg) { var oP = document.createElement('p'); oP.innerHTML = msg; oReply.appendChild(oP); //oReply是全局变量!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } // 创建留言 function createMsg(name, msg) { // 创建标签 var oDD = document.createElement('dd'); // 给标签加内容 oDD.innerHTML = ` <h3> <span>${name}</span> <span>${new Date()}</span> </h3> <p>${msg}</p> <div class="huiFu"></div> <button class="reply_btn">回复</button> <button class="del_btn">删除</button> ` // 把标签插入到页面中 appendChild insertBefore $('dl').insertBefore(oDD, $('dt').nextSibling); // djs 函数 } // 获取所有的 集合 function $(s) { return document.querySelector(s) } </script> </body> </html>