评论区点击查看更多功能的实现
思路:
对内容的高度进行判断,如果内容的高度大于设定的值,将内容的高度设定为固定值,同时将‘查看更多’的节点上树。实现还是挺简单的,直接看代码。
<!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 type="text/css">
/* 这是最外层的容器,这里没有设置高度,所以它的高度是随着内容的变化而变化的 */
.comment {
width: 560px;
padding: 15px 10px;
margin: 10px;
overflow: hidden;
position: relative;
}
/* 清除浮动*/
.comment::after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
/* 这是点击‘查看更多’的样式*/
.span {
position: absolute;
width: 100%;
display: block;
bottom: 0;
cursor: pointer;
color: orangered;
text-align: center;
background: linear-gradient(180deg, rgba(255, 255, 255, 0), #fff);
}
/* 这是头像的样式*/
.img {
height: 48px;
width: 48px;
border-radius: 24px;
display: block;
float: left;
margin-top: 10px;
}
/* 这是评论内容的样式*/
.p {
float: left;
width: 500px;
margin-left: 12px;
}
</style>
</head>
<body>
<!-- 评论书写区 -->
<textarea name="" id="textarea" cols="80" rows="10"></textarea>
<!-- 发布按钮-->
<button class="post">点击发布</button>
<!-- 这是评论列表 -->
<div class="list">
</div>
<script>
const textarea = document.getElementById('textarea');
const list = document.getElementsByClassName('list')[0];
const post = document.getElementsByClassName('post')[0];
//为发布按钮绑定响应事件
post.onclick = function() {
//获取评论书写区的内容并判断
let content = textarea.value;
if (content) {
//创建节点
let discuss = document.createElement('p');
let comment = document.createElement('div');
let more = document.createElement('span');
let img = document.createElement('img');
//为节点添加样式和设置内容
img.className = 'img';
discuss.className = 'p';
more.className = 'span';
comment.className = 'comment';
img.src = '../作业/img/pic_2.jpg';
more.innerHTML = '查看更多';
discuss.innerHTML = content;
//节点上树
comment.appendChild(img);
comment.appendChild(discuss);
list.appendChild(comment);
//判断内容的高度,如果超过100px则设置固定高度并添加‘查看更多’
if (discuss.offsetHeight > 100) {
//alert(comment.offsetHeight)
discuss.style.height = 100 + 'px';
comment.appendChild(more);
}
//为‘查看更多’添加点击事件,将内容的高度设置为auto,并将‘查看更多’隐藏
more.onclick = function() {
discuss.style.height = 'auto';
more.style.display = 'none';
}
} else {
alert("请输入内容");
}
}
</script>
</body>
</html>