2016-02-08 34 views
4

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

当前我使用this approach来产生文本溢出时的省略号(当它不能放入一行时)。但是,现在我还想在发生溢出时在行末添加“Read More”链接,并单击该链接将在多行中显示所有内容。这仅适用于CSS吗?

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

我想最后的手段是使用JavaScript与resize()侦听器动态地隐藏文本溢出部分并创建显示它们的链接。

谢谢!

+1

我没有办法知道使用CSS检测溢出。这个问题似乎证实:http://stackoverflow.com/questions/18844192/css-only-detection-of-text-overflows-in-html。如果你正在寻找一个JS解决方案,看看这个问题:http://stackoverflow.com/questions/7738117/html-text-overflow-ellipsis-detection – Marcelo

回答

-1

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

a.read-more { 
display: none; 
} 

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

如果该类被设置在所有项目,无论内容,则需要使用JavaScript来做到这一点,在里皮的评论说明。

0

这不适用于只有 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>

0

您将需要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 
} 

注意:这回答你的问题的第二部分 - 第一部分是由另一个海报回答。