js文章太长显示部分(百分比),点击按钮显示全部

2024年05月11日 建站教程

功能介绍:文章内容太长,进入页面只显示部分内容,并且提示“展开剩余 76% ↓”,点击按钮显示全部内容!

js代码如下:

document.addEventListener("DOMContentLoaded", function() {
  const fullContent = document.getElementById('content').innerHTML
  if(fullContent.length > 800){
    const partialContent = fullContent.substring(0, 600);
    const percent = (100 -  (600 / fullContent.length) * 100).toFixed(0)
    document.getElementById('content').innerHTML = `${partialContent}<div class="read-box"><div class="read_mask"></div><div class="read_mod"><span class="read-button" id="showFullContent">展开剩余 ` + percent + `% ↓</span></div></div>`;  
    document.getElementById('showFullContent').addEventListener('click', function() {  
      document.getElementById('content').innerHTML = `${fullContent}`;  
      this.style.display = 'none';  
    });
  }
});

css代码如下:

.read-box {
    position: relative;
    z-index: 9;
    margin-top: -220px;
    padding: 0 0 35px;
    width: 101%;
    text-align: center;
}
.read_mask {
    height: 200px;
    background: -webkit-gradient(linear,0 top,0 bottom,from(rgba(255,255,255,0)),to(#fff));
    background: -o-linear-gradient(bottom,rgba(255,255,255,.1),rgba(255,255,255,0));
}
.read-box .read_mod {
    background-color: #fff;
}
.read-button {
    display: inline-block;
    width: 230px;
    height: 45px;
    border: 1px solid #6b0;
    color: #6b0;
    vertical-align: top;
    font-size: 14px;
    line-height: 45px;
    cursor: pointer;
}
.read-button:hover{
    background: #6b0;
    border: 1px solid  #6b0;
    color: #fff;
}

本文链接:http://so.lmcjl.com/news/4270/

展开阅读全文
相关内容