繁体   English   中英

document.execCommand('unlink')不适用于Firefox中的锚点

[英]document.execCommand('unlink') doesn't work for anchors in Firefox

我正在使用document.execCommand("unlink", false, false); 删除我自己的HTML编辑器中的超链接和锚点。 它工作正常,除了一种情况:它不会删除Firefox中的锚点。 这是不是在Firefox中支持,还是有其他方法可以解决这个问题?

这是我的例子:

<div contenteditable="true">This is an <a name="anker">anchor</a>. And this is a <a href="#">normal hyperlink</a>. Please try to select them and then press the "Unlink" button.</div>

<input type="button" id="btn" value="Unlink">

$(document).ready(function() {    
    $('#btn').click(function() {
        document.execCommand("unlink", false, false);
    });
});

在小提琴上看看吧

要回答你什么替代品有问题,你可以强制的问题,并设置任何a元素的href之前调用属性unlink

$(document).ready(function() {    
    var $editable = $('[contenteditable]');

    $('#btn').click(function() {
        $editable.find('a:not([href])').attr('href', '#');
        document.execCommand("unlink", false, false);
    });
});

http://jsfiddle.net/Bz7pR/7/

当然,可能有多种方法可以“解决”这个问题。 我想$.unwrap()可能也会起作用。 我不是很熟悉document.execCommand和富文本编辑器,但我想你需要小心,精确和测试测试。

注意,这只是一个示范; 你真的要考虑这个问题并考虑你将如何处理这个问题。 例如,如果Firefox是浏览器,您可以检测并仅运行它,这将限制您可能遇到的任何意外损坏或结果。

编辑

这是一个更完整的版本,只影响所选的文本范围:

$(document).ready(function() {    
    $('#btn').click(function unlink() {
        var holder,
            frag,
            range,
            child;

        if (window.getSelection && window.getSelection().getRangeAt) {
            holder = document.createElement('div');
            frag = document.createDocumentFragment();
            range = window.getSelection().getRangeAt(0);

            $(holder)
                .append(range.cloneContents())
                .find('a:not([href])')
                .attr('href', '#');

            while ((child = holder.firstChild)) {
                frag.appendChild(child);
            }

            range.deleteContents();
            range.insertNode(frag);
        }

        document.execCommand("unlink", false, false);
    });    
});

http://jsfiddle.net/Bz7pR/12/

在文本范围和选择方面,我不是天才,所以我修改了这个答案中的代码:

https://stackoverflow.com/a/6252893/451969

想出上面的内容。 如果有人看到某些错误或不连贯的内容,请在下面留言。

暂无
暂无

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

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