将keypress和focusout事件附加到contenteditable div中的元素 [英] Attaching keypress and focusout event to elements inside contenteditable div
本文介绍了将keypress和focusout事件附加到contenteditable div中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将keypress
和focusout
事件处理程序附加到可内容编辑的div
内的段落.
I want to attach keypress
and focusout
event handlers to a paragraph inside contenteditable div
.
以下代码似乎无效:
<div contenteditable="true">
<p id="p1">Test</p>
<p id="p2">Test</p>
<p id="p3">Test</p>
</div>
$('#p1').bind('keypress', function(e) {
alert('keypress');
});
$('#p1').focusout(function(e) {
alert('focusout');
});
推荐答案
基本上,contenteditable
是响应内部节点调度的事件的contenteditable
.如果我们获得插入符号的位置,然后将其定位为范围的parentNode,则可以获取所需的ID
Basically the contenteditable
is the one that will respond to events dispatched from the inner Nodes. If we get the caret position and than target it's range's parentNode - than we can retrieve the desired ID
$('[contenteditable]').on('keypress focusout', function(ev) {
var node = window.getSelection().getRangeAt(0).commonAncestorContainer;
var nodeParent = node.parentNode;
// Do something if parent node ID is "p1"
if( nodeParent.id === "p1") {
console.log( nodeParent.id +' '+ ev.type ); // or whatever you need to do here
}
});
<div contenteditable="true">
<p id="p1">TestP1 do someting on keypress</p>
<p id="p2">TestP2 is Not Interesting</p>
</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
这篇关于将keypress和focusout事件附加到contenteditable div中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文