0

我有字符串,例如

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

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

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

这些字符串是从 AJAX 响应中获取的。如何使用 jQuery 实现这一点?

4

1 回答 1

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);
    }
});

哦,是的,顺便说一句,不知道当文本框填满 '> ... >' 时会发生什么 :) GL

于 2013-04-13T21:00:37.703 回答