2016-11-09 24 views
3

我有幾個li,其中包含一些文本。寬度有限,所以用戶可以看到前30個字符。我試圖實現兩件事情,在前30個字符後面加上...(顯然...應該在展開模式下消失),第二件事是能夠展開li以顯示整個文本。目前,該文本默認情況下是擴展的,無法理解爲什麼。CSS JS - 默認情況下,long li文本被擴展(應該隱藏溢出)

fiddle這裏。

HTML:

<div> 
    <ul> 
    <li id="a">normal length text</li> 
    <li id="b">this is a relatively long text</li> 
    <li id="c">this is an example of a really long text</li> 
    <li id="d">this is an example of an extremely long, pointless text. this is an example of an extremely long, pointless text</li> 
    </ul> 
</div> 

CSS:

div { 
    width: 250px; 
} 

div ul { 
    text-align: left; 
    padding: 0 10px; 
} 

ul li { 
    list-style-position: inside; 
    overflow: hidden; 
    //text-overflow: elipsis; 
} 

JS:

$("li").on("click", function() { 
    var titleLength = $(this).context.innerHTML.length; 
    if (titleLength > 30) { 
    if ($(this).height() == 18) { 
    $(this).css('height', 'auto'); 
    var height = $(this).height(); 
     $(this).height(18).animate({height: height}, 200) 
    } else { 
     $(this).animate({ 
     height: 18 
     }, 200) 
    } 
    } 
}); 
+0

其「省略號」不是「省略號」..注意雙字母。 –

回答

3

你不給你li元素的任何限制height默認情況下,這意味着它們默認爲auto ,因此包含整個字符串。

由於jQuery代碼設置自己的身高在關閉時18像素,只需添加以下內容:

ul li { 
    height: 18px; 
    ... 
} 

Modified JSFiddle


最重要的是:

  1. 你拼寫爲 「省略號」 錯誤地在你的text-overflow財產。
  2. text-overflow屬性將被忽略,但未指定添加值爲nowrapwhite-space屬性。
  3. 這樣做後,你需要刪除並重新添加white-space財產內的jQuery。

這裏的another modified JSFiddle demo以上所有考慮。

1

首先,設置爲ellipsis,而不是elipsis,請注意雙l。此外,您不限制li元素的大小,因此該設置不起作用。您需要在元素上設置一個width,以及默認情況下停止包裝元素。

爲了實現擴展邏輯,您可以在點擊時切換一個班級,取消使用text-overflow工作所需的CSS規則。試試這個:

$("li").on("click", function() { 
 
    $(this).toggleClass('expand'); 
 
});
div { 
 
    width: 250px; 
 
    background-color: lightgrey; 
 
} 
 
div ul { 
 
    text-align: left; 
 
    padding: 0 10px; 
 
} 
 
ul li { 
 
    list-style-position: inside; 
 
    width: 100%; 
 
    overflow: hidden; 
 
    white-space: nowrap; 
 
    text-overflow: ellipsis; 
 
} 
 
ul li.expand { 
 
    white-space: normal; 
 
    overflow: visible; 
 
    text-overflow: clip; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    <ul> 
 
    <li id="a">normal length text</li> 
 
    <li id="b">this is a reletively long text</li> 
 
    <li id="c">this is an example of a really long text</li> 
 
    <li id="d">this is an example of an extremdsfsdfs sgdfdsfgdfg ertwerr wee www ely long, pointless text</li> 
 
    </ul> 
 
</div>

0

沒有必要javascript添加...溢出李後

ul li { 
    list-style-position: inside; 
    overflow: hidden; 
    text-overflow: elipsis; 
    white-space: nowrap; 
    text-overflow: ellipsis; 
} 

然後改變white-space屬性當點擊李

$("li").on("click", function() { 
    $(this).css('white-space','normal'); 
}); 

親自試一試https://jsfiddle.net/tcfLgom9/3/