javascript - contenteditable div 中的链接

标签 javascript html jquery

我正在尝试创建一个可编辑的 div,它会定期检查输入的任何与 @text 匹配的文本(以@开头,以空格结尾)。

例如,如果用户输入 @text more text here , 它会将以 @ 开头并以空格结尾的单词更改为类似 <a href="#">@text</a> more text here 的链接在 div 中。

我已经开始使用 JSFiddle,但是,我无法让它工作:http://jsfiddle.net/MpFXK/2/

HTML:

<div class="box" contenteditable="true"></div>

JS:

$(document).on('keyup', ".box", function() {
    var text = $(this).text();
    var regexp = /\B@([^\B ]+)/;
    if (text.match(regexp)) {      
        text = text.replace(/\B@([^\B ]+)/, '<a href="#">/\B@([^\B ]+)/</a> ');
        return $(this).html(text);
    }
    return false;
});

请帮忙!

最佳答案

fiddle

$(document).on('keyup', ".box", function(e) {
    if (e.keyCode == 32) {
        var text = $(this).text();
        var regexp = /(?=[@])[*@]\w+/;

        var newText = text.replace(regexp, function(match) {
            return '<a href="#">' + match + '</a>'
        });
        $(this).html(newText);
        setEndOfContenteditable(this);
    }
});

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

credit对于 setEndOfContenteditable 函数

关于javascript - contenteditable div 中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623123/

相关文章:

javascript - Typeahead.js 远程可以工作,但预取不能

javascript - 获取当前选择的选项

javascript - 如何链接使用 emcc 从 cpp 文件编译的 .bc 文件和项目符号库?

javascript - 自动完成搜索框并将值传递给 flask

php - 如何在论坛页面中监控用户

javascript - 仅适用于平板电脑/手机的 JS 脚本

javascript - $scope 在 ionic 应用程序中返回未定义

jquery - 使用 jQuery 将两个元素的大小调整为最大的一个

javascript - 下拉列表中填充了数据库数据,并在按钮单击时添加

javascript - jQuery 在 AJAX 请求中使用回调中断循环