contenteditable div中子元素的键盘事件? [英] Keyboard events for child elements in a contenteditable div?

查看:206
本文介绍了contenteditable div中子元素的键盘事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其contenteditable属性已设置为true.如何让孩子们响应键盘事件?似乎唯一的方法是在父div中捕获事件并通过选择api确定子项.有没有更好的办法?更具体地说,我可以将键盘事件处理程序附加到子元素吗?我想念什么吗?

I have a div who's contenteditable property has been set to true.How do I get the children to respond to keyboard events? Seems like the only way is to capture the events in the parent div and figure out the child via the selection apis. Is there a better way? More specifically, can I attach a keyboard event handler to child elements? Am I missing something?

随附的示例代码说明了该问题.希望代码中的注释具有足够的解释性.

Attached is sample code that illustrates the problem. Hope the in-code comments are sufficiently explanatory.

<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>

<BODY>
<div id="editable" contentEditable='true' style='height: 130px; width: 400px; border-style:solid; border-width:1px'>
    <span id="span1" onkeypress="alert('span1 keypress')">test text 1</span> <!-- does not work -->
    <span id="span2" > test text2</span>
    <span id="span3" onclick="alert('span3 clicked')">test text 3</span>  <!-- this works fine -->
</div>
<!-- Uncomment this to set a keypress handler for span2 programatically. still doesnt work -->
<!--
<script type="text/javascript">
    var span2 = document.getElementById('span2');
    span2.onkeypress=function() {alert('keypressed on ='+this.id)};
</script>
-->

<!-- Uncomment this to enable keyboard events for the whole div. Finding the actual child that the event is happening on requires using the selection api -->
<!--
<script type="text/javascript">
    var editable = document.getElementById('editable');
    editable.onkeypress=function() {alert('key pressed on ='+this.id+';selnode='+getSelection().anchorNode.parentNode.id+',offset='+getSelection().getRangeAt(0).startOffset)};
</script>
-->
</BODY>
</HTML>

推荐答案

这是因为常规的span和div无法获得焦点.您可以通过向标签添加tabindex属性或使其可编辑来使正常跨度或div可聚焦.您不希望在子跨度上使用tabindex,因为这似乎阻止了它在IE中可编辑.我打算建议检查整个div传递给keypress处理程序的Event对象的target/srcElement属性,但是在IE中,这只能为您提供对同一div的引用,而不是子范围

It's because regular spans and divs are incapable of receiving focus. You can make a normal span or div focusable by adding a tabindex attribute to the tag, or by making it editable. You don't want a tabindex on the child span because this seems to prevent it being editable in IE. I was going to suggest examining the target / srcElement properties of the Event object passed to the keypress handler for the whole div but in IE this only gives you a reference to the same div rather than the child span.

因此,在回答您的问题时,我认为没有比使用选择检查字符输入位置更好的跨浏览器解决方案了.

So in answer to your question, I don't believe there is a better cross-browser solution than using the selection to check where the character was typed.

这篇关于contenteditable div中子元素的键盘事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆