JS动态更改div高度实现代码例子
作者:洋哥登陆
在Web开发中通过使用JavaScript可以动态地修改HTML元素的属性和样式,下面这篇文章主要给大家介绍了关于JS动态更改div高度实现的相关资料,文中给出了详细的代码示例,需要的朋友可以参考下
前言
通过JS动态更改div高度。高度大于限定值内容进行折叠,显示view more。点击后显示全部内容。
js代码
<html>
<body onload="queryHeight()">
<!-- div容器 -->
<div class="container">
<!-- 文本内容 高度可能为1000以上 -->
</div>
<div id="readMore" class="readMore">
<div class="readBackground"></div>
<div class="readText" onclick="show()"> Read more ∨</div>
</div>
<script>
var contentHeight = 0
function queryHeight() {
const content = document.getElementsByClassName('container')[0]
// 要获得真实高度,需用 onload 来执行方法
contentHeight = content.offsetHeight
if(content.offsetHeight > 800){
content.style.height = 800
content.style.overflow = 'hidden'
}
}
function show() {
const content = document.getElementsByClassName('container')[0]
content.style.height = contentHeight
content.style.overflow = ''
const readMore = document.getElementById('readMore')
readMore.style.display = 'none'
}
</script>
</body>
</html>
<style>
body{
margin: 0px;
width: 100%;
height: 100%;
background-color: #EFEFEF;
}
.container{
width: 100%;
height: 1500px;
background-color: #FFFFFF;
}
.td-content{
height: auto;
}
/* read-more */
.readMore{
position: absolute;
width: 100%;
height: 60px;
text-align: center;
font-size: 14px;
font-family: 'Roboto-Regular, Roboto';
font-weight: 600;
color: #000000;
line-height: 40px;
}
.readBackground{
width: 100%;
height: 20px;
background: linear-gradient(180deg, rgba(255,255,255,0) 0%, #FFFFFF 100%);
}
.readText{
background-color: #FFFFFF;
}
</style>效果
点击前

点击后

总结
到此这篇关于JS动态更改div高度实现的文章就介绍到这了,更多相关JS动态更改div高度内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
