HTML 粘贴事件,将粘贴区域限制为 div 边框
HTML Paste-Event, limit paste area to div border
我在 html-div-element 使用粘贴事件让用户粘贴图像。
我希望用户在粘贴图片时站在 div 上。
所以我将粘贴事件绑定到 div
选择器。
问题是每次用户按下 ctrl+v 时都会触发事件,即使鼠标没有站立在 div.
我试图检查 event.currentTarget
- 也许我可以问它是否是 div
,但它总是给我 div
选择器,即使 ctrl+v 当我在其他元素上时发生。
这是我的代码:
HTML:
<div id="myPasteZone" style="border:1px solid black;height: 150px;width: 35vw"></div>
Javascript(打字稿):
$('#myPasteZone').bind("paste", (e)=>{
const file = e.originalEvent.clipboardData.files[0];
if(file){
this.addNewAttachment(file);
}
});
有什么方法可以限制粘贴事件只在div
吗?
试试这个。我将 tabIndex
添加到 div 以便它可以聚焦。然后只有聚焦时才能粘贴。
演示:(ctrl + v)
$(document).ready(function() {
$('#myPasteZone').bind("paste", (e) => {
try {
if ($(":focus")[0].id === "myPasteZone") { // check if div focused
const file = e.originalEvent.clipboardData.files[0];
if (file) {
this.addNewAttachment(file);
}
console.log('pasted');
}
} catch (e) {
return;
} // catch if id not exist
});
});
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<body>
<div id="myPasteZone" tabindex="-1" style="border:1px solid black;height: 150px;width: 35vw"></div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <p>hello, world</p>
</body>
我在 html-div-element 使用粘贴事件让用户粘贴图像。
我希望用户在粘贴图片时站在 div 上。
所以我将粘贴事件绑定到 div
选择器。
问题是每次用户按下 ctrl+v 时都会触发事件,即使鼠标没有站立在 div.
我试图检查 event.currentTarget
- 也许我可以问它是否是 div
,但它总是给我 div
选择器,即使 ctrl+v 当我在其他元素上时发生。
这是我的代码:
HTML:
<div id="myPasteZone" style="border:1px solid black;height: 150px;width: 35vw"></div>
Javascript(打字稿):
$('#myPasteZone').bind("paste", (e)=>{
const file = e.originalEvent.clipboardData.files[0];
if(file){
this.addNewAttachment(file);
}
});
有什么方法可以限制粘贴事件只在div
吗?
试试这个。我将 tabIndex
添加到 div 以便它可以聚焦。然后只有聚焦时才能粘贴。
演示:(ctrl + v)
$(document).ready(function() {
$('#myPasteZone').bind("paste", (e) => {
try {
if ($(":focus")[0].id === "myPasteZone") { // check if div focused
const file = e.originalEvent.clipboardData.files[0];
if (file) {
this.addNewAttachment(file);
}
console.log('pasted');
}
} catch (e) {
return;
} // catch if id not exist
});
});
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<body>
<div id="myPasteZone" tabindex="-1" style="border:1px solid black;height: 150px;width: 35vw"></div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <p>hello, world</p>
</body>