2016-02-08 32 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 
} 

注意:這回答你的問題的第二部分 - 第一部分是由另一個海報回答。