限制输入字段的实时预览中显示的字符数

时间:2014-02-06 10:03:51

标签: javascript jquery input

当我在输入字段中输入文字时,该值会在p元素中实时显示:http://jsfiddle.net/HC9KD/

如何在预览中仅显示多达25个第一个字符? 我尝试使用本网站上的一些方法,但它们似乎对我不起作用。

text-overflow: ellipsis - 不会这样做。

欣赏任何想法。

HTML

<p id="preview"></p>
<input type="text" id="typedtext">

的JavaScript

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('preview').innerHTML = this.value;
}

4 个答案:

答案 0 :(得分:2)

试试这个:http://jsfiddle.net/HC9KD/1/

使用记录为hereslice()

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('preview').innerHTML = this.value.slice(0,25);
}

更新

我从ragatskynet中获取了这个想法,如果输入的字符数超过25个字符,则在末尾添加点。请参阅此处的jsfiddle:http://jsfiddle.net/HC9KD/7/

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    document.getElementById('preview').innerHTML = this.value.slice(0,25) + function(x) {
        if(x.length > 25) { return " ..."} else {return ""};
    }(this.value);
}

答案 1 :(得分:0)

您可以使用substr()

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    if(this.value.length <= 25){
        document.getElementById('preview').innerHTML = this.value;    
    } else {
        document.getElementById('preview').innerHTML = this.value.substr(0,25) + "...";
    }
 }

http://jsfiddle.net/HC9KD/4/

答案 2 :(得分:0)

http://jsfiddle.net/HC9KD/3/

var wpcomment = document.getElementById('typedtext');

wpcomment.onkeyup = wpcomment.onkeypress = function(){
    if (document.getElementById('preview').innerText.length < 25) {
        document.getElementById('preview').innerHTML = this.value;
    }
}

答案 3 :(得分:0)

试试这个......

var wpcomment = document.getElementById('typedtext');
var count=1;
wpcomment.onkeyup = wpcomment.onkeypress = function(){
    if(count<=50){
         document.getElementById('preview').innerHTML = this.value;

     }
     count++;
 }