簡體   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