jQuery学习笔记--制作简易留言板
功能实现
点击发布,通过下滑方式展示留言。点击删除,通过上滑方式删除留言。没有本地存储,所以刷新之后会重置。
运行结果
代码实现
<!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>
.box {
width: 500px;
border: 1px solid #000;
padding: 20px;
margin: 100px auto;
}
.text {
width: 360px;
height: 190px;
outline: none;
resize: none;
}
li {
list-style: none;
width: 409px;
height: 25px;
line-height: 25px;
border-bottom: 1px dashed #ccc;
margin-left: 27px;
display: none;
}
.box li a {
float: right;
}
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<div class="box">
<span>留言板</span>
<textarea name="" id="" cols="30" rows="10" class="text"></textarea>
<button>发布</button>
<ul></ul>
</div>
<script>
$("button").on("click", function () {
var li = $("<li></li>");
li.html($(".text").val() + "<a href=javascript:;>删除<a>");
$("ul").prepend(li);
li.slideDown();
$(".text").val("");
})
$("ul").on("click", "a", function () {
$(this).parent().slideUp(function () {
$(this).remove();
})
})
</script>
</body>
</html>
笔记
- 必须在css中加一句display:none,才会有滑入、淡入效果。
- 用到了事件委托,注意在$("ul").on("click", "a", function () { $(this).parent().slideUp(function () { $(this).remove(); }) }) 中不同this的指向。
- 是先要上滑再删除,用到了slideUp的回调函数。
