2014-02-06 142 views
0

如I型在輸入字段中的文本,在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; 
} 

回答

2

試試這個:http://jsfiddle.net/HC9KD/1/

使用slice()作爲記錄here

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

你的第一個例子中的作品爲我好。我很欣賞這裏的所有答案。 – qwaz

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/

+0

在我看來,if語句在這裏是多餘的。 'substr'仍然適用於字符數少於用作截止限制的字符數的字符串。 – Xiphias

+0

當然(我原來的代碼是按照你的想法寫的),但是如果你不到25個字符,你就不需要添加點。 – ragatskynet

+0

點是一個很酷的想法,確實如此:-) – Xiphias

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; 
    } 
} 
+0

如果文本的長度爲25個字符或更多,這不會預覽任何內容,是不是? – Xiphias

+0

它會。嘗試一下。 – justtal

+0

好的,對不起。你有一個點。儘管如此,一旦達到了字符限制,在我的例子中,在零到二十五個字符的部分中再也沒有更新。你注意到了嗎? – Xiphias

0

嘗試......

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

    } 
    count++; 
}