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>

效果

点击前
在这里插入图片描述

点击后
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Peanutfight/article/details/130297813
今日推荐