【问题标题】:Generating ellipsis AND "Read more" link with CSS使用 CSS 生成省略号和“阅读更多”链接
【发布时间】:2016-02-08 15:35:46
【问题描述】:

[更新] 这与这个问题不同,因为它不仅要求截断文本;正如我所提到的,我已经使用this approach 进行了文本截断。而是询问仅在文本被截断时才具有“阅读更多”链接(仅在可能的情况下使用 CSS)。

目前我正在使用this approach 在文本溢出时生成省略号(当它无法放入一行时)。但是,现在我还想在发生溢出时在行尾包含一个“阅读更多”链接,单击该链接将显示多行的所有内容。这仅适用于 CSS 吗?

顺便说一句,我看到this post,无论文本是否溢出,它都会显示“更多”链接,这不是我想要的。

我猜最后的办法是使用带有resize() 侦听器的javascript,它动态隐藏文本的溢出部分并创建链接以显示它们。

谢谢!

【问题讨论】:

标签: javascript html css


【解决方案1】:

为此,您将需要 JS。你可以在 jQuery 中做这样的事情:

var str = "this is some truncated te..."; //Your string to eval
var n = str.search("..."); //look for the elepsis 
if (n ==="" || n === null){ //if the elepsis is not found in the string
   $(".foo").hide(); //hide your read more link
}else{
   $(".foo").show(); //show your read more link
}

注意:这回答了您问题的第二部分 - 第一部分由另一位发帖人回答。

【讨论】:

    【解决方案2】:

    只有 CSS 无法做到这一点。

    这是我相当老套的解决方案:在 JavaScript 中,删除 .truncate 类以获得未截断的宽度,然后如果文本的宽度会导致它被截断,则生成一个阅读更多链接。

    var truncated = document.getElementsByClassName("truncate");
    
    for (var i = 0; i < truncated.length; i++) {
        var t = truncated[i];
    
        // Remove the truncate class to get at the un-truncated width
        t.classList.remove("truncate");
        t.style.display = "inline-block";
        // w = un-truncated width
        var w = t.clientWidth;
        // Restore styling
        t.style.display = "";
        t.classList.add("truncate");
    
        // 250 corresponds to the width in the CSS
        if (w >= 250) {
            // Generate read more link
            var readMore = document.createElement("a");
            readMore.href = "#";
            readMore.innerText = "Read More";
            t.parentNode.insertBefore(readMore, t.nextSibling);
        }
    }
    .truncate {
        width: 250px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    <div class="truncate">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui iusto quos praesentium et cupiditate nostrum, suscipit voluptates sint eos amet vel quisquam, consequuntur hic necessitatibus, quibusdam ex repellat error odio.</div>
    <hr>
    <div class="truncate">Hello</div>

    【讨论】:

      【解决方案3】:

      如果您使用 CSS 类来截断文本,为什么不使用相同的类来隐藏或显示链接?

      a.read-more {
      display: none;
      }
      
      .truncate a.read-more {
      display: block;
      }
      

      如果无论内容如何都为您的所有项目设置了类,则您需要使用 JavaScript 来完成,如 Marcello 的评论中所述。

      【讨论】:

        猜你喜欢
        • 2013-03-12
        • 2019-02-21
        • 2014-11-18
        • 2018-09-09
        • 2017-03-14
        • 2013-02-10
        • 2011-08-18
        • 2016-10-18
        • 2011-08-02
        相关资源
        最近更新 更多