【问题标题】:Keyboard events for child elements in a contenteditable div?contenteditable div中子元素的键盘事件?
【发布时间】:2010-11-05 04:52:08
【问题描述】:

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

附件是说明问题的示例代码。希望代码中的 cmets 有足够的解释性。

<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>

【问题讨论】:

    标签: keyboard-events contenteditable


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2021-10-09
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多