2016-08-05 26 views
0

假設我們有如下的html。如何知道刪除密鑰關閉的確切段落?

<div class="my_content" contenteditable="true"> 
    <div class="my_paragraph"><span style="color:red;">RED</span><span style="color:green;">GREEN</span></div> 
    <div class="my_paragraph"><span style="font-size:1em">1EM-TEXT</span><div> 
    <div class="my_paragraph"><span style="font-size:2em">2EM-TEXT</span><div> 
</div> 

而且我有一個如下所示的Backbone查看器。

events: { 
    "keydown .my_paragraph" :"onKeyDown" 
}, 

onKeyDown : function(e) { 
    if(e.keyCode === 46) { //delete key 
    } 
} 

問:在「如果」的方法的onkeydown,我怎樣才能得到確切的段落,這是用戶試圖刪除(通過按下刪除鍵)?

+0

它也將取決於你放置刪除按鈕的位置 – Sherlock

回答

1
onKeyDown : function(e) { 
    if(e.keyCode === 46) { //delete key 
    } 
} 

你希望在你的例子是帕拉姆e 您可以標識要傳遞的事件是什麼段落集中使用e.target對象

更新:


至於什麼derek說,divs不能聽按鍵事件,除非你把content editable設置爲true。

對於這項工作,除去父母div的CONTENTEDITABLE並將此屬性設置在每個孩子的

$(function(){ 
 
    $('.my_paragraph').on('keydown', function(e){ 
 
     console.log(e.target); 
 
    }); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="my_content"> 
 
    <div class="my_paragraph first" contenteditable="true"><span style="color:red;">RED</span>"><span style="color:green;">GREEN</span></div> 
 
    <div class="my_paragraph second" contenteditable="true"><span style="font-size:1em">1EM-TEXT</span></div> 
 
    <div class="my_paragraph third" contenteditable="true"><span style="font-size:2em">2EM-TEXT</span></div> 
 
</div>

+0

這仍然會返回包含'contenteditable =「true」' –

+0

@DerekStory的'.my_content',它取決於焦點字段 – Sherlock

+0

它不會。對於不包含'contenteditable =「true」''的'div',沒有焦點字段。使用當前的例子(使用空格鍵) - http://codepen.io/anon/pen/kXAowA?editors=1010#0 –

1

你可以做線沿線的東西:

var cursorTarget = getSelection().getRangeAt(0).commonAncestorContainer.parentNode; 
var targetParagraph = $('.my_paragraph').has(cursorTarget); 
targetParagraph.addClass('target-paragraph'); // Or whatever you want 

Codepen Example(使用空格鍵例如)


同樣重要:您的html無效。您在最後兩個.my_paragraph div中沒有​​正確使用關閉</div>標籤,並且在關閉第一個span後還有一個額外的">

+0

這個工程!非常感謝您回答我的問題。然而,我試圖不使用getSelection,因爲它不是一個標準,而且有太多不同的方法來取決於瀏覽器。我希望如果可能,我可以換一種方式 –

+0

感謝您的更正。我將編輯它 –

+0

您可能需要更強大的功能來獲取光標位置。或者將'contenteditable =「true」'應用於單個'.my_paragraph' divs,但我有一種不希望的感覺。 –