开发者

function to shorten a text dynamically inside span

i have a span like this.

css:
.menu {border:1px solid #000; width:200px; display:block; padding:3px;}

html:
<span class="menu">This is an example text</span&开发者_Go百科gt;
<span class="menu">Another text example</span>

It prints this.

function to shorten a text dynamically inside span

i have set the "span width" to 200px, because of the text is longer then 200px, so the span is resized to more than 200px.

I need a javascript or jQuery function so it'll print something like this. It also add "..." in the end of the text.

function to shorten a text dynamically inside span

A css style would also be accepted...


I think that the CSS property text-overflow is what you're looking for. Browser support is not awesome though. But where it's not supported maybe just cutting the text without ellipsis is ok?


If you don't have a requirement to use ellipsis (...), a cross-browser pure-CSS approach is:

  1. Set a fixed with to your container and set the overflow CSS property to hidden.
  2. Create a shim/overlay that masks a small portion of the right end of the container. Give this shim a background image that is a gradient from transparent to the background color of the container.
  3. Text that is too long will be clipped.
  4. The shim with the gradient will give the clipped text a nice fade out effect.

function to shorten a text dynamically inside span


Try this out buddy ....

<title>untitled</title>
<style type="text/css" media="screen">
    .hide{
            display: none;
    }
    span.menu{border:1px solid #000; width:200px; display:block; padding:3px;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
    $(function(){
            var $element = $('span');             // The element or elements with the text to hide
            var $limit = 26;                // The number of characters to show
            var $str = $element.html();        // Getting the text
            var $strtemp = $str.substr(0,$limit);   // Get the visible part of the string
            $str = $strtemp + ' ...<span class="hide">' + $str.substr($limit,$str.length) + '</span>';  // Recompose the string with the span tag wrapped around the hidden part of it
            $element.html($str);               // Write the string to the DOM 
    })
</script>

Loren Ipsum Loren Ipsum Loren Ipsum Loren Ipsum Loren Ipsum Loren Ipsum Loren Ipsum Loren Ipsum Loren Ipsum Loren Ipsum

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜