如何在粘贴上获取textarea输入字段的新值? [英] How to get the new value of a textarea input field on paste?
问题描述
我看到当我尝试在调用textarea的 onpaste
函数时从textarea字段读取值时,我得到的是字段的旧值(粘贴操作之前的值),而不是新值(粘贴操作后的值).
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).
以下是此行为的演示: http://jsfiddle.net/qsDnr/
Here is a demonstration of this behaviour: http://jsfiddle.net/qsDnr/
代码副本如下:
<!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.
- 将字符串
foo
复制到剪贴板. - 右键单击textarea字段,然后选择粘贴".div元素中没有任何内容.
- 右键单击textarea字段,然后再次选择粘贴".
foo
出现在div元素中.
- 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.
由于我希望div元素始终显示通过粘贴操作在textarea元素中进行了更新,因此所需的输出是步骤2中的 foo
和 foo foo
第3步.
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.
我设法获得所需输出的一种方法是通过使用 window.setTimeout()
延迟 update()
函数调用,而不是
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
我有
textareaElement.onpaste = function() {
window.setTimeout(update, 100);
};
这次(演示: http://jsfiddle.net/cwpLS/).这就是我想要的.但是,这感觉更像是一种解决方法,而不是一种直接的方式来完成我想要的事情.我想知道是否还有其他更好的方法可以做到这一点.
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.
推荐答案
我很确定setTimeout解决方案是实现所需效果或尝试访问剪贴板对象的唯一方法-如果您遇到这种情况,它可能会变得混乱打算跨浏览器&旧的浏览器支持.
I'm pretty sure that you setTimeout solution is the only way to achieve the desired effect, or try to access the clipboard object - which can get messy if you're going for cross-browser & old browser support.
这篇关于如何在粘贴上获取textarea输入字段的新值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!