<h1>留言板<h1>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>留言板</title>
<style type="text/css">
*{margin: 0;padding: 0;}
#wrap{
width: 370px;
border:1px solid rgb(193,193,193);
padding: 20px;
background: rgb(243,243,243);
}
#txt1{
width: 315px;
height: 20px;
}
#s1{
display: inline-block;
position: relative;
top: -140px;
}
#btn1{
width: 100px;
height: 30px;
font-size: 16px;
color: rgb(100,100,100);
background: rgb(249,249,249);
border:1px solid rgb(203,203,203);
margin-left: 40px;
}
#h2{
padding-top:10px;
}
a{
float: right;
}
</style>
</head>
<body>
<!-- 結構 -->
<div id="wrap">
<span>姓名:</span>
<input type="text" id="txt1"><br><br>
<span id="s1">內容:</span>
<textarea name="" id="txta" cols="50" rows="10" style="resize: none;"></textarea><br><br>
<button id="btn1">提交</button>
<h2 id="h2">顯示留言</h2>
<div id="main"></div>
</div>
<!-- 行為 -->
<script>
function bind(){
//獲取元素
var txt = document.getElementById('txt1');
var txta = document.getElementById('txta');
var btn = document.getElementById('btn1');
var wrap = document.getElementById('wrap');
//提交按鈕的點擊事件
btn.onclick = function click(){
//創建兩個 p 標簽和一個div
var p1 = document.createElement('p');
var p2 = document.createElement('p');
//創建一個div來包裹p1和p2
var main = document.createElement('div');
//將輸入的內容分別給兩個 p 標簽
var con1 = txt.value;
var con2 = txta.value;
//把txt和txta里面的內容給p1和p2,然后在網頁中打印出來
p1.innerHTML = con1;
p2.innerHTML = con2 + "<a href='###'>刪除</a>";
//判斷當用戶沒輸入內容時彈出提示
if(txt.value == "" || txta.value == ""){
alert('用戶名或內容未填寫');
}else{
//將 p 標簽的內容添加到一個大的div里面
main.appendChild(p1);
main.appendChild(p2);
//將div里內容添加到主頁面wrap中
wrap.appendChild(main);
}
//點擊提交按鈕清空文本框和文本域里的內容
txt.value = "";
txta.value = "";
//p1的樣式
p1.style.height = '40px';
p1.style.paddingLeft = '10px';
p1.style.backgroundColor = 'rgb(220,220,220)';
p1.style.borderBottom = '1px solid rgb(203,203,203)';
p1.style.lineHeight = '40px';
//p2的樣式
p2.style.height = '30px';
p2.style.paddingLeft = '50px';
p2.style.backgroundColor = 'rgb(253,253,253)';
p2.style.borderBottom = '1px solid rgb(203,203,203)';
p2.style.lineHeight = '30px';
//
main.style.transition = 'all 2s';
//a標簽的獲取和點擊事件
var anchor = p2.getElementsByTagName('a');
anchor[0].onclick = function(){
//移除對象
wrap.removeChild(main);
}
}
}
bind();
</script>
</body>
</html>
Paste_Image.png
Paste_Image.png
![Upload Paste_Image.png failed. Please try again.]
Paste_Image.png