如何防止IE10中意外删除可信的ul? [英] How to prevent accidental deletion of contenteditable ul in IE10?

查看:113
本文介绍了如何防止IE10中意外删除可信的ul?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在页面上有一个可疑的ul。但是,在Internet Explorer 10中,如果单击它,使用右键单击菜单或CTRL + A选择all,然后删除,ul元素将从页面中删除。

I want to have a contenteditable ul on a page. However, in Internet Explorer 10, if you click into it, select all with either the right click menu or CTRL+A, then delete, the ul element gets deleted off the page.

防止这种情况的最佳方法是什么,或者至少检测到它何时发生并插入替换ul?

What is the best way to prevent this, or at least detect when it happens and insert a replacement ul?

推荐答案

我建议拦截删除和退格键并手动执行删除操作。步骤如下:

I'd suggest intercepting the delete and backspace keys and doing the delete manually. The steps are:


  • 获取所选范围

  • 调整范围的末尾可编辑的< ul> 元素(如果它们在外面)

  • 调用 deleteContents()在范围内。

  • Get the selected range
  • Adjust the ends of the range to lie within the editable <ul> element if they are outside
  • Call deleteContents() on the range.

注意以下内容不适用于IE< = 8.如果您需要支持这些浏览器,您可以使用我的 Rangy 库,它也可用于简化 deleteSelectedContent()略。

Note the following won't work on IE <= 8. If you need to support those browsers, you could use my Rangy library, which could also be used to simplify deleteSelectedContent() slightly.

演示: http://jsfiddle.net / timdown / STcXa / 3 /

代码:

var editor = document.getElementById("editor");

function deleteSelectedContent() {
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount > 0) {
            var range = sel.getRangeAt(0);
            var editorRange = range.cloneRange();
            editorRange.selectNodeContents(editor);

            // Adjust selection range boundaries
            if (range.compareBoundaryPoints(Range.START_TO_START, editorRange) == -1) {
                range.setStart(editorRange.startContainer, editorRange.startOffset);
            }
            if (range.compareBoundaryPoints(Range.END_TO_END, editorRange) == 1) {
                range.setEnd(editorRange.endContainer, editorRange.endOffset);
            }

            range.deleteContents();
        }
    }
}

editor.addEventListener("keydown", function(evt) {
    if (window.getSelection &&
            !window.getSelection().isCollapsed &&
            (evt.keyCode == 8 || evt.keyCode == 46)) {
        evt.preventDefault();
        deleteSelectedContent();
    }
}, false);

这篇关于如何防止IE10中意外删除可信的ul?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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