开发者

Adjust width based on parent and add elipsis w/jQuery

I need to adjust the width of an element based on parent's width and add an ellipsis at the end. Here's what I've got. Looks straight forward but I can't seem to be able to add ellipsis. What did I miss?

<style>
.my开发者_开发知识库Class{
    white-space: nowrap;
    overflow: hidden;
}
</style>

$(".myClass").each(function() {
    var str = $(this);
    var par = str.parent().width();
    var newWidth = par - 20; // to allow room for ellipsis
    str.width(newWidth);
    str.append("...");
});


<div style="width: 100px">
    <span class="myClass">My long text string here. Even longer goes on and on.</span>
</div>


Had to make a few changes. The biggest is that display:hidden means that the ... you add will be clipped off. You need to append that ... to the parent element. Also, I changed the span to display:inline-block; so that display:hidden would work properly.

http://jsfiddle.net/u6XfD/

Note: This is not a great idea since as you can see in that fiddle, it may cut characters off in the middle.


instead of .append() try str.text(str.text()+"&hellip;");


$(".myClass").each(function() {
    var str = $(this);
    var par = str.parent().width();
    var newer = par - 20; // to allow room for ellipsis
    str.width(newer);
    $("...").appendTo(str);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜