2014-06-27 25 views
1

我試圖找出一個CONTENTEDITABLE格,看起來像這樣內的光標的直接父(段落元素):獲取keydown事件的父元素,jQuery的

<div id=base> 
<div ce='1' contenteditable='true'> 
<p id='unique'>Paragraph one</p> 
<p>Paragraph two</p> 
</div> 
</div> 

如果我綁定。點擊事件的'ce'div,則event.currentTarget被報告爲發生點擊的段落。但跟蹤光標我需要使用.keydown事件

$('#base').on({ 
    keydown: function(event) { 
     myLog(' nodeName: '+event.currentTarget.nodeName); 
    }, 
// With the following selector the event is triggered with the cursor 
// anywhere in 'ce', and .currentTarget is the 'ce' div. 
}, '[ce]'); 
// With this selector the event is never triggered regardless of cursor position 
}, '#unique'); 

爲什麼沒有被觸發的情況下,我如何能實現我的目標是什麼?

回答

0

我不認爲你可以從事件對象中獲取元素,因爲在#base上觸發事件,所以#base是目標(而不是文本節點或段落)。

您可以使用當前所選內容在事件發生時獲取包含光標的容器(textnode),並使用該容器搜索段落。

這可能是這樣的:

$('#base').on({ 
    keydown: function(event) { 
    // get current selection 
    var selection = window.getSelection(); 
    if (selection.rangeCount === 1) { 
     // get container of cursor 
     var textnode = selection.getRangeAt(0).startContainer; 

     // use jquery to get paragraph 
     console.log($(textnode).parents('p')); 
    } 
    } 
}); 

這只是一個很簡單的(不跨瀏覽器),例如(在FireFox測試)。對於真正的代碼,你將不得不做更多的檢查來獲取當前的光標位置。爲了使您的生活更輕鬆,你可以看一下四肢瘦長:

https://code.google.com/p/rangy/

這是處理選擇庫。