1
4

4 回答 4

5

You can handle it by using css instead of using any javascript. There is text-overflow in css for making the effect ... when the string is over the width. If you would like to show the original text, you would add :hover in css to remove the overflow boundary.

The alternative is using javascript to count the content length and modify the content with ellipsis. Also, if you want to show original text, use hover() but you have to store the original text first.

So, there are two solutions, check this for detail: http://jsfiddle.net/zqfhx/1/

CSS

<style type="text/css">
.w100C {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;    
    width: 100px;
    min-width: 0;
}

.w100C:hover {  
    overflow: none;
    width: auto;
}
</style>

HTML

<div class="w100C">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever s
</div>

Alternative method with Javascript(jQuery)

JavaScript

$(document).ready(function() {

    function TruncateText(text)
    {
        if(text.length > 12)
        {
             text = txt.substring(0,12) + "...";
        }
        return text;
    }

    var txt = $("#abc").text();
    $("#abc").attr("orgTxt", txt);
    txt = TruncateText(txt);
    $("#abc").text(txt);

    $("#abc").hover(function(){
        var t = $("#abc").attr("orgTxt");
        $("#abc").text(t);
    }, function(){
        var t =  $("#abc").text();
        t = TruncateText(t);
        $("#abc").text(t);
    });    
});

HTML

<div id="abc">I am very long string</div>

Personally, I will recommend to use CSS instead of JavaScript as it can handle multiple element by styling and reducing the script execution.

于 2013-03-05T15:14:16.120 回答
3

This doesn't need jQuery

var str = "whatever here"
var shortened = str.length > 15 ? str.substring(0,12) + '...' : str;
于 2013-03-05T15:07:52.807 回答
0

If you are just trying to "fit" based on element size, you may want to try text-overflow.

JSFiddle for illustrative purposes

Moz Docs for text-overflow

于 2013-03-05T15:14:27.410 回答
0

Assuming your content goes within a div with id "content" and your string is saved within a longString variable

$(document).ready(function() {
    var contentDiv = $("#content");
    contentDiv.html(longString.substr(0,12) + "...");

    contentDiv.mouseover(function(){ 
         this.html(longString);
    });

    contentDiv.mouseout(function(){
         this.html(longString.substr(0,12) + "...");
    });
});

This is untested, but it should give you the show and hide functionality you need. It also assumes the string is always at least 12 characters. If error checking is needed, you can add it easily.

于 2013-03-05T15:16:42.980 回答