4

165 文字で構成されるテキストがいくつかあります。最初の 155 文字だけを表示する必要がありますが、155 文字のうち最後の 5 文字を「.....」(省略記号) に置き換え、残りの文字を削除する必要があります。フィドル

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
    $(function(){
        var txt= $('div').text();
        for(i=0;i<2;i++){
            alert(txt.charAt(150+ i))
        }
    })
</script>
</head>
<body>
<div style="width:100px">
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that
</div>
</body>
4

5 に答える 5

5

ターゲットにしているブラウザーによっては、css を使用することもできます。

text-overflow: ellipsis
于 2013-05-30T15:48:42.043 に答える
2

TecHunter はすでにほぼ同じものを投稿しているようですが、退屈してこれを行いました。

155 文字では、最後の 5 文字が「....」に置き換えられます。入力時に更新される文字カウンターを備えたテキストエリア入力があります。

HTML

<div>
    <h2>Input</h2>
    <textarea id="sampleInput">
    It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.     The point of using Lorem Ipsum is that
    </textarea>
</div>
<div>
    <label>Character Count:</label> <span id ="charCounter"></span>
<div>
<h2>Output</h2>
<p style="width:100px" id="sampleOutput"></p>

JS

updateOutput();

$('#sampleInput').keyup(function(e){
   updateOutput();
});

function updateOutput(){
    var sampleInput = $('#sampleInput').val(),
        sampleInputLength = sampleInput.length;

    if(sampleInputLength >= 155) {    
        sampleInput = sampleInput.substr(0,150) + ".....";    
    }

    $('#charCounter').text(sampleInputLength);
    $('#sampleOutput').text(sampleInput);
}

CSS

#sampleInput {
    width: 400px;
    height:100px;    
}

jsfiddle

于 2013-05-30T16:00:54.790 に答える
1

ちなみに、いくつかの良い答えを見ましたが、他のケースでは効率的でないものもあります。たとえば、何かをコピーして貼り付けるときなどです。だから、私は提案します:

 $(document).on('keyup keypress blur change', '#elementId', function () {
     var maxLength = 100; // number of characters to limit
     imposeMaxLength($(this), maxLength);
 });

 function imposeMaxLength(element, maxLength) {
     if (element.val().length > maxLength) {
         element.val(element.val().substring(0, maxLength));
     }
 }

imposeMaxLength を関数として使用すると、他のイベントで再利用できます。

于 2017-05-08T20:38:05.810 に答える