Retrieve parent node from selection (range) in Gecko and Webkit

前端 未结 3 1932
北恋
北恋 2021-02-09 20:37

I am trying to add an attribute when using a wysiwyg editor that uses \"createLink\" command. I thought it would be trivial to get back the node that is created after the browse

3条回答
  •  轮回少年
    2021-02-09 21:12

    I have found that selection can get complicated and buggy across browsers. Throw in the magic of browser document editing, and it gets worse!

    I took a look at how TinyMCE implements what I am trying to do, and took the same approach to modify jHtmlArea.

    Basically, a link is created with a fake href. Then, it finds that dom element by searching for links with that particular href. You can then add any desired attributes and update the href with the actual url.

    The solution above by gnarf is a great example of getting a selected node, and will work for most scenarios.

    Below is the code for my work around:

    var url = prompt("Link URL:", "http://");
    
    if (!url) {
        return;
    }
    
    // Create a link, with a magic temp href
    this.ec("createLink", false, "#temp_url#");
    
    // Find the link in the editor using the magic temp href
    var linkNode = $(this.editor.body).find("a[href='#temp_url#']");
    
    linkNode.attr("rel", "external");
    
    // Apply the actual desired url
    linkNode.attr("href", url);
    

提交回复
热议问题