问题
Hi I am setting up a live preview of the input of a textarea which will be posted to a blog. I currently have this set up
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:" onkeypress="document.getElementById('prevCom').innerHTML = this.value"></textarea>
<div id="prevCom"></div>
The issue is that the preview is one character behind the input of the textarea. For instance if i write "my comment" I see "my commen"
Thanks for your help!
回答1:
Use keyup and keypress events, keyup alone won't work if someone holds down a key and it repeats.
var wpcomment = document.getElementById('WPComment');
wpcomment.onkeyup = wpcomment.onkeypress = function(){
document.getElementById('prevCom').innerHTML = this.value;
}
DEMO
回答2:
Instead of onkeypress="..."
Change to onkeyup
. This will fix the issue your having with the with the characters not updating as expected.
So your final code should be:
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:" onkeyup="document.getElementById('prevCom').innerHTML = this.value"></textarea>
<div id="prevCom"></div>
Check out this JSFiddle
回答3:
Try this
<textarea name="WPcomment" id="WPComment" placeholder="Add comments:" onkeyup="document.getElementById('prevCom').innerHTML = this.value"></textarea>
<div id="prevCom"></div>
Use onkeyup
instead of onkeypress
here is the demo
回答4:
You can change with onkeyup or onchange
onkeyup ="document.getElementById('prevCom').innerHTML = this.value"
回答5:
onkeyup
event in javascript will take the letter as soon you press it
来源:https://stackoverflow.com/questions/12270749/live-preview-of-textarea-input-with-javascript-html