在详情页获取的文字数据过长,实现加载全文的功能

  当我们从后台获取数据后,希望能够将较长的文章截取, 出现一个点击加载全文的按钮, 这样会有更好的用户体验。

  实现思路极为: 在文章的末尾添加一个“加载全文”的按钮,先将其的display属性设置为none,然后,我们获取数据,判断其行数是否超过某一个特定的值,如果是,我们就限定content的高度,然后overflow:hidden; 然后再将按钮的display设置成block,然后添加事件,当点击时content的高度恢复,然后按钮的display属性设置位none即可,代码如下:

    var content = document.querySelector(".article-content");
    var height = parseInt(window.getComputedStyle(content).height);
    var line_height = parseInt(window.getComputedStyle(content).lineHeight);
    var rows = parseFloat(height/line_height)/2;
    var initial_height = rows*line_height;
    var show_more = document.querySelector(".show-more");
    var show_more_btn = document.querySelector("#show_more_btn");
    if(rows>20){
        show_more_btn.style.display = "block";
        content.style.height = initial_height + "px";
        content.style.overflow = "hidden";
        show_more_btn.onclick = function () {
            showMore()
        };
        function showMore () {
            show_more_btn.style.display = "none";
            show_more.style.display = "none";
            content.style.height = height + "px";
        }
        
    }
原文地址:https://www.cnblogs.com/zhuzhenwei918/p/6421266.html