[英]Truncate Text in ul li anchor tag
Here is my html , 这是我的HTML,
<ul class="test">
<li><a href="#">python</a></li>
<li><a href="#">Truncate should apply here </a></li>
<li><a href="#">c</a></li>
<li><a href="#">cpp</a></li>
<li><a href="#">java</a></li>
<li><a href="#">.net</a></li>
<li><a href="#">This is really a long text in this ul </a></li>
<li><a href="#">This is another really a long text in this ul </a></li>
</ul>
I want to truncate the text in anchor tag , if the length of text is higher than 6 chars. 如果文本的长度高于6个字符,我想截断锚标记中的文本。
The output should like , 输出应该像,
python
Trun..
c
cpp
java
.net
This..
This..
How can i do this using Jquery ? 我怎么能用Jquery做到这一点?
You can do something like this: 你可以这样做:
$('ul.test li a').each(function() {
var text = $(this).text();
if(text.length > 6) {
$(this).text(text.substring(0, 4) + '..')
}
});
If you want to use pure CSS then you can use text-overflow: ellipsis
property: 如果你想使用纯CSS,那么你可以使用text-overflow: ellipsis
属性:
ul.test li a {
width: 45px;
display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
However, you cannot control the number of limited characters before putting ellipsis using this approach. 但是,在使用此方法放置省略号之前,您无法控制有限字符的数量。
Try below CSS 试试下面的CSS
a {
width: 50px;
display: block;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
You can use a vanilla JS solution and save some resources (and it's short too): 您可以使用vanilla JS解决方案并节省一些资源(也很简单):
var As = document.getElementsByTagName("a"); // all the `a` elements
for(var i = 0, len = As.length;i < len; i++){ // iterate over them
// cut them by 6 characters, and set the new value
As[i].innerHTML = As[i].innerHTML.substr(0, 6);
}
Or, you can use the text-overflow property in CSS if you don't want to cut the text and lose it forever. 或者,如果您不想剪切文本并永久丢失,则可以在CSS中使用text-overflow属性。
You can use the following as a start and combine it with some if..else statements to get the desired output. 您可以使用以下内容作为开头,并将其与一些if..else语句组合以获得所需的输出。
$(".test li a").each(function(index){
$(this).text($(this).text().substring(0,4)+"...")
})
Another way of doing it using CSS can be found at this JSFiddle Demo: http://jsfiddle.net/7Ues5 使用CSS的另一种方法可以在这个JSFiddle演示中找到: http : //jsfiddle.net/7Ues5
This will do it. 这样做。
$(document).ready(function () {
$("button").click(function () {
for (i = 0; i < $("a").length; i++)
{
if ($("a")[i].text.length > 6)
{
$("a")[i].text = $("a")[i].text.substring(0,4)+"..";
}
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.