使用jquery在文本框中挤压字符

时间:2013-04-13 20:56:00

标签: javascript jquery

我有字符串,例如

Computer > Software > Programming Language > Python
Computer > Software > Game > BT4

如果字符串不适合文本框的宽度,我想挤压并显示如下所示:

Computer > Software > ...> Python
Computer > Software > Game > BT4

字符串是从AJAX响应中获得的。我怎样才能用jQuery实现这个目标?

1 个答案:

答案 0 :(得分:1)

这可以帮助您解决问题:

https://github.com/STAR-ZERO/jquery-ellipsis

甚至

<击> http://dotdotdot.frebsite.nl/

<强>更新

以下是我提出的问题:Jsfiddle

appendList = ['Computer', 'Software', 'Programming Language', 'Python'];
idx = -1;
$('#appendButton').on('click', function() {
    if (idx++ >= appendList.length-1)
        return;
    var inputField = $('#inputField'),
        value = inputField.val();
    inputField.val(value + ((idx == 0) ? appendList[idx]:' > ' + appendList[idx]));
        value = inputField.val();
    // Check the length based on the "size" of the input.
    if (value.length >= 30) {
         // Get the last "section"
        var startPos = (value.lastIndexOf('>')-1),      
            begStr  = value.slice(0, startPos - 1),
            saveStr = value.slice(startPos);

        // Now we need the last occurrence of '>', 
        // This will give you multiple occurrences of '...'
        var secStartPos = begStr.lastIndexOf('>')+2;

        // Or you can use these two lines, instead
        // of the ones below if you only ever want
        // one '...', but to always show the last "section"
        //
        // var secStartPos = begStr.indexOf('>')+2;
        // while ((secStartPos = begStr.lastIndexOf('>', secStartPos)+2) >= 30) { };
        //
        var secSaveStr = begStr.slice(0, secStartPos);

        // Now append '...'
        secSaveStr += '...';

        // Rebuild the string.
        var finalStr = secSaveStr + saveStr;

        inputField.val(finalStr);
    }
});

哦是的BTW,不知道当文本框填满'&gt;时这是做什么的......&gt;' :) GL