Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在contenteditable元素中插入链接_Javascript_Jquery_Hyperlink_Contenteditable - Fatal编程技术网

Javascript 在contenteditable元素中插入链接

Javascript 在contenteditable元素中插入链接,javascript,jquery,hyperlink,contenteditable,Javascript,Jquery,Hyperlink,Contenteditable,我正在开发一个简单的博客系统,我正在使用contenteditable,这样用户就可以格式化文本 到目前为止,一切都很顺利 接下来我想要的是,用户可以在文本中添加超链接 用户必须选择(部分)文本并单击链接按钮。之后,将打开一个弹出窗口,用户应在其中输入链接地址 当用户单击accept按钮时,我想将链接添加到他们在contenteditable中选择的文本 既然我不知道如何实现这个功能,我该如何实现这个功能 我的网站: jsFiddle of my site:正如alfred所说,已经有了完善的编

我正在开发一个简单的博客系统,我正在使用contenteditable,这样用户就可以格式化文本

到目前为止,一切都很顺利

接下来我想要的是,用户可以在文本中添加超链接

用户必须选择(部分)文本并单击链接按钮。之后,将打开一个弹出窗口,用户应在其中输入链接地址

当用户单击accept按钮时,我想将链接添加到他们在contenteditable中选择的文本

既然我不知道如何实现这个功能,我该如何实现这个功能

我的网站:


jsFiddle of my site:

正如alfred所说,已经有了完善的编辑器,尤其是基本功能的编辑器。您可以将其限制为使用尽可能少或尽可能多的功能

从头开始开发它的困难之处在于,所有浏览器的行为都略有不同。以下应能让您在大多数浏览器(IE除外)中朝着正确的方向前进:

var selected = document.getSelection();
document.execCommand("insertHTML",false,"<a href='"+href+"'>"+selected+"</a>");
var selected=document.getSelection();
document.execCommand(“insertHTML”,false,”);
document.execCommand()
可在所有主要浏览器中为您执行此操作:

document.execCommand("CreateLink", false, "http://stackoverflow.com/");
要在显示链接对话框时保留选择,可以使用以下功能:

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            var ranges = [];
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                ranges.push(sel.getRangeAt(i));
            }
            return ranges;
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(savedSel) {
    if (savedSel) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            for (var i = 0, len = savedSel.length; i < len; ++i) {
                sel.addRange(savedSel[i]);
            }
        } else if (document.selection && savedSel.select) {
            savedSel.select();
        }
    }
}
。。。或类似以下内容:

function getLinksInSelection() {
    var selectedLinks = [];
    var range, containerEl, links, linkRange;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            linkRange = document.createRange();
            for (var r = 0; r < sel.rangeCount; ++r) {
                range = sel.getRangeAt(r);
                containerEl = range.commonAncestorContainer;
                if (containerEl.nodeType != 1) {
                    containerEl = containerEl.parentNode;
                }
                if (containerEl.nodeName.toLowerCase() == "a") {
                    selectedLinks.push(containerEl);
                } else {
                    links = containerEl.getElementsByTagName("a");
                    for (var i = 0; i < links.length; ++i) {
                        linkRange.selectNodeContents(links[i]);
                        if (linkRange.compareBoundaryPoints(range.END_TO_START, range) < 1 && linkRange.compareBoundaryPoints(range.START_TO_END, range) > -1) {
                            selectedLinks.push(links[i]);
                        }
                    }
                }
            }
            linkRange.detach();
        }
    } else if (document.selection && document.selection.type != "Control") {
        range = document.selection.createRange();
        containerEl = range.parentElement();
        if (containerEl.nodeName.toLowerCase() == "a") {
            selectedLinks.push(containerEl);
        } else {
            links = containerEl.getElementsByTagName("a");
            linkRange = document.body.createTextRange();
            for (var i = 0; i < links.length; ++i) {
                linkRange.moveToElementText(links[i]);
                if (linkRange.compareEndPoints("StartToEnd", range) > -1 && linkRange.compareEndPoints("EndToStart", range) < 1) {
                    selectedLinks.push(links[i]);
                } 
            }
        }
    }
    return selectedLinks;
}
函数getLinksInSelection(){
var selectedLinks=[];
变量范围、容器、链接、链接范围;
if(window.getSelection){
sel=window.getSelection();
if(sel.getRangeAt&&sel.rangeCount){
linkRange=document.createRange();
对于(var r=0;r-1){
selectedLinks.push(links[i]);
}
}
}
}
linkRange.detach();
}
}else if(document.selection&&document.selection.type!=“控制”){
range=document.selection.createRange();
containerell=range.parentElement();
if(containerell.nodeName.toLowerCase()=“a”){
选择链接。推送(ContaineReel);
}否则{
links=containerEl.getElementsByTagName(“a”);
linkRange=document.body.createTextRange();
对于(变量i=0;i-1和&linkRange.compareEndPoints(“结束到开始,范围)<1){
selectedLinks.push(links[i]);
} 
}
}
}
返回所选链接;
}
jsFiddle:

在IE in Execcommand中编辑它是不可能的,因为我们不能在“href”中插入引号,我们必须在纯javascript中进行编辑,范围为:

//在一个IFRAME中的DIV中

//无框DIV


我会这样做:

  • 创建一个带有(可能是唯一的)初始伪
    href
    属性的链接,以通过以下方式识别它
  • 使用
    document.querySelector('a[href=]”)获取该元素
  • 现在您有了一个对已创建元素的引用,可以随意处理它
  • 这样做的好处是,您根本不必使用
    选择。

    更好看的答案:

    函数链接(){
    if(window.getSelection().toString()){
    var a=document.createElement('a');
    a、 href='http://www.google.com';
    a、 标题=‘谷歌’;
    window.getSelection().getRangeAt(0).surroundContents(a);
    }
    }
    选择一些文本,然后单击链接按钮!
    
    将文本链接到谷歌
    谢谢你。适用于大多数浏览器。我真的没想到默认情况下它会在IE下工作。还有一点是新的:)现在唯一发生的事情是,当我尝试输入URL时,我的文本上不再设置选择。因此,我无法添加超链接。有没有办法在执行execCommand之前保留/重置选择?因为您对contentEditable区域使用的是

    ,所以您使用的是相同的文档元素,因此当您单击任何位置时,您将丢失上一个选择。尝试使用
    Enter
    键作为提交方式,而不是单击检查图标。否则,您可以通过保留范围来获得更深入的信息,请参考@PeeHaa,@clmarquart:使用
    document.execCommand()的“CreateLink”命令执行所有浏览器所需的操作。看看我的答案。@Tim,你说得对。尽管如此,我还是更喜欢使用
    insertHTML
    ,即使它需要为IE做一些额外的工作。通过这种方式,您可以直接控制插入的HTML,比如添加
    标题
    属性。放下。你是我永远的英雄!最后,我可以摆脱那个丑陋的javascript提示窗口;)尽管我认为克莱·马卡尔的观点是正确的。接下来我要做的是创建一个带有目标(_blank)的链接,我想我需要insertHTML(或其他东西)来实现这一点。是否可以通过将目标添加到
    a
    标记使代码正常工作?如果可以的话,你不仅是我的英雄,而且我会将你的身份升级为上帝!:)@皮哈阿:问得好。这将是棘手的,因为
    function getLinksInSelection() {
        var selectedLinks = [];
        var range, containerEl, links, linkRange;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                linkRange = document.createRange();
                for (var r = 0; r < sel.rangeCount; ++r) {
                    range = sel.getRangeAt(r);
                    containerEl = range.commonAncestorContainer;
                    if (containerEl.nodeType != 1) {
                        containerEl = containerEl.parentNode;
                    }
                    if (containerEl.nodeName.toLowerCase() == "a") {
                        selectedLinks.push(containerEl);
                    } else {
                        links = containerEl.getElementsByTagName("a");
                        for (var i = 0; i < links.length; ++i) {
                            linkRange.selectNodeContents(links[i]);
                            if (linkRange.compareBoundaryPoints(range.END_TO_START, range) < 1 && linkRange.compareBoundaryPoints(range.START_TO_END, range) > -1) {
                                selectedLinks.push(links[i]);
                            }
                        }
                    }
                }
                linkRange.detach();
            }
        } else if (document.selection && document.selection.type != "Control") {
            range = document.selection.createRange();
            containerEl = range.parentElement();
            if (containerEl.nodeName.toLowerCase() == "a") {
                selectedLinks.push(containerEl);
            } else {
                links = containerEl.getElementsByTagName("a");
                linkRange = document.body.createTextRange();
                for (var i = 0; i < links.length; ++i) {
                    linkRange.moveToElementText(links[i]);
                    if (linkRange.compareEndPoints("StartToEnd", range) > -1 && linkRange.compareEndPoints("EndToStart", range) < 1) {
                        selectedLinks.push(links[i]);
                    } 
                }
            }
        }
        return selectedLinks;
    }
    
    // Get the frame
    var iframe = document.getElementById('myframe');
    
    // Selection object in the frame
    theSelection = iframe.contentWindow.getSelection();
    
    // position of the selection to insert
    theRange = theSelection.getRangeAt(0);
    
    // get content inside the original selection (and delete content in)
    var fragment = theRange.extractContents();
    
    // Create a new link in frame
    var newLink = iframe.contentWindow.document.createElement('a');
    
    // Create a text element with the fragment to put in the link
    var theText = document.createTextNode(fragment.textContent);
    
    // URL 
    theLink.href = '#';
    
    // Title
    theLink.title = 'title';
    
    // Attribute 'onclick'
    theLink.setAttribute('onclick', thelink);
    
    // Target
    theLink.target = '_blank';
    
    // Add the text in the link
    theLink.appendChild(theText);
    
    // Insert the link at the range
    theRange.insertNode(newLink);
    
    // Selection object in the window
    theSelection = window.getSelection();
    
    // begin of the selection to insert
    theRange = theSelection.getRangeAt(0);
    
    // get content inside the original selection (and delete content in)
    var fragment = theRange.extractContents();
    
    // Create a new link in the document
    var newLink = document.createElement('a');
    
    // Create a text element with the fragment to put in the link
    var theText = document.createTextNode(fragment.textContent);
    
    // URL 
    theLink.href = '#';
    
    // Title
    theLink.title = 'title';
    
    // Attribute 'onclick'
    theLink.setAttribute('onclick', thelink);
    
    // Target
    theLink.target = '_blank';
    
    // Add the text in the link
    theLink.appendChild(theText);
    
    // Insert the link at the range
    theRange.insertNode(newLink);