这个想法是在页面级别处理粘贴事件(与在单个输入字段/元素级别处理它相反)。解决方案是将粘贴事件处理程序绑定到顶级 div 元素。
问题是,在粘贴事件开始触发之前,用户必须在页面首次加载后首先物理单击浏览器窗口内的任何位置(即使浏览器窗口本身处于焦点位置)。
问题是:如何在没有此步骤(必须在窗口内单击)的情况下使页面对粘贴敏感?
我尝试过但不起作用的技术:
- 以编程方式将外部 div 集中在加载上(参见下面的 js 代码)
- 在加载时以编程方式单击外部 div(请参见下面的 js 代码)
注意:我的实际项目是一个相当复杂的 Angular 网页,幸运的是,我能够使用纯 HTML/javascript 复制该行为。
注意: div 上的粘贴事件似乎仅在 Chrome 中有效。所以不要在 MSIE 或 FF 中尝试这个。不过,跨浏览器支持是另一个我想单独解决的问题。
测试 html 页面以复制问题:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>paste test</title>
<style type="text/css">
html, body {
padding: 0;
margin: 0;
height: 100%;
}
div#outer {
margin: auto;
height: 100%;
padding: 20px;
background-color: whitesmoke;
box-sizing: border-box;
}
div#inner {
margin: auto;
margin-top: 20px;
padding: 20px;
width: 500px;
height: 500px;
border: solid 3px green;
}
</style>
</head>
<body onload="load()">
<div id="outer" onpaste="paste()" tabindex="1">
First click anywhere to make the paste work.
<div id="inner">
Just any content.
Not important for example.
</div>
</div>
<script type="text/javascript">
function load() {
document.getElementById('outer').focus();
document.getElementById('outer').click();
}
function paste() {
alert('paste');
}
</script>
</body>
</html>