简体   繁体   English

如何通过单击可删除的div,然后使用Jquery在键盘上按Delete键来删除它?

[英]How can I delete an editable div by clicking on it and then pressing the Delete key on the keyboard with Jquery?

I have a div with the attribute contenteditable = true. 我有一个属性为contenteditable = true的div。 I can activate the div content editing by double clicking the div, this is because my div is draggable, so I use the dooble click event to activate the div edition. 我可以通过双击div来激活div内容编辑,这是因为我的div是可拖动的,所以我使用dooble click事件来激活div版本。 The fact is that I want to eliminate the complete div by clicking on it and then pressing the Delete key on the keyboard. 事实是,我要消除整个div,方法是单击它,然后按键盘上的Delete键。 How can I do that? 我怎样才能做到这一点? How can I make it so that when I write something on the div and press the delete key, the entire div will not be deleted? 如何使它在div上写东西并按Delete键时不会删除整个div? I only want to delete the div when the div edition is not activated, just click on the div and then hit the delete key and voila, it is deleted. 我只想在未激活div版本时删除div,只需单击div,然后按Delete键,瞧,它将被删除。

This is my HTML Code: 这是我的HTML代码:

 $(document).ready(function() { $('.draggable').draggable({ containment: "parent" }); $(".draggable").resizable(); $('#MyFirstDiv').click(function() { //HERE I WANT TO PUT THE CODE TO DELETE THE DIV. }); $("#myContainer").on("dblclick", "#MyFirstDiv", function(e) { e.preventDefault(); $(".draggable").draggable('disable'); this.querySelector(":scope > :first-child").focus(); }); $("#myContainer").on("blur", "#MyFirstDiv", function(e) { e.preventDefault(); $(".draggable").draggable('enable'); }); }); 
 #myContainer { border: 1px solid black; height: 400px; width: 100%; } #DraggableDiv { border: 1px solid blue; } 
 <!DOCTYPE html> <html> <head> <title>My Delete Div</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> </head> <body> <div id="myContainer"> <div id="MyFirstDiv"> <div class="draggable" contenteditable="true" id="DraggableDiv"> THIS IS MY TEXT INSIDE THE DIV </div> </div> </div> </body> </html> 

Easiest way to to capture the keydown on the delete key. 捕获删除键上的keydown的最简单方法。

$('#MyFirstDiv').click(function(e){
   e.preventDefault(); 
});
$('#MyFirstDiv').keydown(function(e){
    e.preventDefault();
    if(e.keyCode == 46) {
        this.remove();
    }
});

You could first just make a variable: divClicked , I store the clicked state of the div 您可以首先制作一个变量: divClicked ,我存储div的clicked状态

var divClicked = false;

Then in your event listener, update divClicked (it'll be a toggled button): 然后在您的事件监听器中,更新divClicked (它将是一个切换按钮):

$("#MyFirstDiv").click(function(e) {
    e.preventDefault();
    divClicked = !divClicked;
}

Finally, add a delete key event listener like so: 最后,添加一个删除键事件侦听器,如下所示:

$("#MyFirstDiv").keydown(function(e) {
    e.preventDefault();
    if (e.keyCode == 46) {
        if (divClicked) {
            $(this).remove();
        } else {
            alert("Click the div first then press Delete to remove it");
        }
    }
})

Full code: 完整代码:

var divClicked = false;

$("#MyFirstDiv").click(function(e) {
    e.preventDefault();
    divClicked = !divClicked;
}

$("#MyFirstDiv").keydown(function(e) {
    e.preventDefault();
    if (e.keyCode == 46) {
        if (divClicked) {
            $(this).remove();
        } else {
            alert("Click the div first then press Delete to remove it");
        }
    }
})

It is not advisable to use Delete while the content is being edited. 在编辑内容时,建议不要使用“ 删除 ”。 You will want to ensure that the user can click the <div> element itself without editing the content. 您将要确保用户可以单击<div>元素本身而无需编辑内容。

Since the <div> is draggable, I would advise using a handle since the click event and keypress events may get capture for content editing and not for your script. 由于<div>是可拖动的,因此我建议使用手柄,因为click事件和keypress事件可能会捕获内容编辑而不是脚本。

 $(function() { function disDrag(part) { var drag = part.closest(".draggable"); drag.draggable("disable"); $(".drag-content", drag).removeAttr("contenteditable").blur(); part.toggleClass("ui-icon-locked ui-icon-unlocked"); } function enDrag(part) { var drag = part.closest(".draggable"); drag.draggable("enable"); $(".drag-content", drag).attr("contenteditable", true).focus(); part.toggleClass("ui-icon-locked ui-icon-unlocked"); } function delDrag(part) { var drag = part.closest(".draggable"); var res = confirm("Are you sure you wish to delete this item?"); if (res) { drag.remove(); } } $('.draggable') .draggable({ containment: "parent", handle: ".ui-drag-handle", start: function() { $(".ui-drag-handle", this).data("selectable", false); }, stop: function() { $(".ui-drag-handle", this).data("selectable", true); } }) .resizable(); $(".ui-drag-handle") .data("selectable", true) .click(function(e) { var drag = $(this).closest(".draggable"); if ($(this).data("selectable")) { drag.toggleClass("drag-selected"); } }); $(".btn").click(function(e) { switch (true) { case $(this).hasClass("ui-icon-unlocked"): disDrag($(this)); break; case $(this).hasClass("ui-icon-locked"): enDrag($(this)); break; case $(this).hasClass("ui-icon-close"): delDrag($(this)); break; } }); $(document).keyup(function(e) { if (e.which == 46 && $(".drag-selected").length) { delDrag($(".drag-selected")); } }); }); 
 #myContainer { border: 1px solid black; height: 400px; width: 100%; } .draggable { border: 1px solid blue; } .draggable.drag-selected { border: 1px solid #0f0; } .center { margin-left: 50%; } .right { float: right; } .ui-icon.btn { border: 1px solid #ccc; border-radius: 3px; margin-top: 0px; margin-left: 1px; } 
 <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <div id="myContainer"> <div class="draggable ui-widget" id="DraggableDiv"> <div class="ui-widget-header"> <span class="right ui-icon ui-icon-close btn" title="Delete the item."></span> <span class="right ui-icon ui-icon-unlocked btn" title="Lock and disable Drag"></span> <div class="ui-drag-handle" style="width: calc(100% - 42px);"> <span class="center ui-icon ui-icon-grip-dotted-horizontal"></span> </div> </div> <div class="drag-content" contenteditable="true"> THIS IS MY TEXT INSIDE THE DIV </div> </div> </div> 

You can see that this is draggable, resizable, and editable. 您可以看到它是可拖动,可调整大小和可编辑的。 The user can disable drag by clicking the lock icon. 用户可以通过单击锁定图标来禁用拖动。 If the select the div and click Delete (or key code 46), or they click the close icon, they will be prompted to confirm that they want to delete the item. 如果选择div并单击Delete(或键代码46),或者单击关闭图标,则将提示他们确认要删除该项目。 Once they confirm that Yes they want to, the item is removed. 一旦他们确认想要,就将其删除。

Since the delete could be triggered by two different ways, I created a delete function. 由于可以通过两种不同的方式触发删除,因此我创建了一个删除功能。

In regards to structure, you may not be able to get away with such simple HTML structures when dealing with more complex UI interactions. 关于结构,在处理更复杂的UI交互时,您可能无法摆脱这种简单的HTML结构。 This one <div> element had all sorts of interactions tied to the click event. 这个<div>元素具有与click事件相关的各种交互。 The user clicks to edit, select, drag... It is better to make more specific targets for some of these events so that you can better script your events. 用户单击以进行编辑,选择,拖动...最好为这些事件中的某些事件指定更具体的目标,以便更好地编写事件脚本。

You could save yourself a lot of time by using Dialog Widget: https://jqueryui.com/dialog/ 您可以使用Dialog Widget节省很多时间: https : //jqueryui.com/dialog/

Hope that helps. 希望能有所帮助。

Test 测试

  • Click on the text to select. 单击文本以选择。
  • Press D to delete. 按D删除。 [sadly delete key didn't work on stack overflow. [严重的删除键在堆栈溢出时不起作用。 Simply change the key code in the if statement to change the key from D to DELETE] 只需在if语句中更改密钥代码,即可将密钥从D更改为DELETE]

Explanation 说明

There are two functions that help solve this problem. 有两个功能可以帮助解决此问题。
Select : Selected the div clicked. 选择 :选择单击的div。
EventListener: Listens for the keypress and deletes the selected div. EventListener:侦听按键并删除选定的div。

Select function 选择功能

  1. Global variable selected stores the information on the div selected. 选定的全局变量将信息存储在选定的div上。
  2. In select function we are fetching the id name of the div clicked by using currentTarget.id from the event object 'e'. 在select函数中,我们使用事件对象'e'中的currentTarget.id来获取单击的div的ID名称。
  3. If statements inside the select function select and deselect the div. 选择函数中的if语句选择并取消选择div。

EventListener 事件监听

  1. Uses event object from the keypress listener to fetch the key pressed. 使用来自按键监听器的事件对象来获取按下的按键。
  2. e.keyCode gives the key. e.keyCode提供密钥。 e.which is a fallback. e。这是一个后备广告。 [for ie users] [针对用户]
  3. If they keyCode is 100 (D key), then use the selected variable to get the selected div and change its css display to 'none'. 如果它们的keyCode为100(D键),则使用选定的变量获取选定的div,并将其CSS显示更改为“无”。

Additionally there is a else statement, where u can add js to when nothing is selected and the key is pressed. 此外,还有一条else语句,您可以在未选择任何内容并按下键的情况下向其中添加js。
Also the css for class selected is for feedback of when the div is selected. 同样,所选类的css也用于选择div时的反馈。


Here is the code snippet: 这是代码片段:

 let selected; const select = e => { //If already selected, this will deselect the div if(selected == e.currentTarget.id) { document.getElementById(selected).classList.remove('selected'); //some CSS selected = null; } else { //select this div selected = e.currentTarget.id; document.getElementById(selected).classList.add('selected'); //some CSS } } window.addEventListener('keypress', e => { //Get key pressed let key = e.keyCode || e.which; if(selected != undefined) { if(key == 100) {//If D is pressed let target = document.getElementById(selected); //get the div target.style.display = 'none'; //hide div console.log('deleted: ' + selected); } } else { //Runs if nothing is selected. Do as you please here. } }) 
 .selected { background: black; color: white; } #DraggableDiv { user-select: none; cursor: pointer; font-family: sans-serif; width: 400px; text-align: center; padding: 10px 5px; } 
 <!DOCTYPE html> <html> <head> <title>My Delete Div</title> </head> <body> <div id="myContainer"> <div id="MyFirstDiv"> <div id="DraggableDiv" onclick="select(event)"> Click me and press D </div> </div> </div> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM