How to get the new value of a textarea input field on paste?

I see that when I try to read the value from a textarea field when its onpaste function is called, I get the old value of the field (the one before the paste operation), not the new value (the one after the paste operation).

Here is a demonstration of this behaviour: http://jsfiddle.net/qsDnr/

A copy of the code follows:

<!DOCTYPE html>
<html>
<head>
<title>On Paste</title>
<script type="text/javascript">
var textareaElement;
var previewElement;

function update()
{
    previewElement.innerHTML = textareaElement.value;
}

window.onload = function() {
    textareaElement = document.getElementById('textarea');
    previewElement = document.getElementById('preview');
    textareaElement.onpaste = update    
}
</script>
</head>
<body>
<textarea id="textarea">
</textarea>
<div id="preview">
</div>
</body>
</html>

You can confirm the behaviour with the following steps.

  • Copy the string foo to your clipboard.
  • Right-click on the textarea field and select 'Paste'. Nothing appears in the div element.
  • Right-click on the textarea field and select 'Paste' again. foo appears in the div element.
  • Since I want the div element to always show what was updated in the textarea element with the paste operation, the desired output is foo and foo foo in step 2 and step 3 respectively.

    One way I have managed to get the desired output is by delaying the update() function call with window.setTimeout() , so instead of

    textareaElement.onpaste = update    
    

    I have got

    textareaElement.onpaste = function() {
        window.setTimeout(update, 100);
    };
    

    this time (demo: http://jsfiddle.net/cwpLS/). This does what I want. However, this feels more like a workaround rather than a straightforward way of doing what I want. I would like to know if there is any alternate or better way to do this.


    我非常肯定你设置Timeout解决方案是实现理想效果的唯一方法,或者尝试访问剪贴板对象 - 如果您想要支持跨浏览器和旧浏览器,可能会变得杂乱无章。


    There is no direct way to do it in cross browser. See the link below about the behaviour in firefox.

    Mozilla

    There is currently no DOM-only way to obtain the text being pasted; you'll have to use an nsIClipboard to get that information.

    Also please have a look at the stackoverflow link which discuss about other possibilities.

    链接地址: http://www.djcxy.com/p/10568.html

    上一篇: 无法将Facebook访问令牌扩展到60天

    下一篇: 如何获取粘贴的textarea输入字段的新值?