javascript / jquery使用contenteditable突出显示语法

时间:2017-02-07 17:48:07

标签: javascript jquery

我遇到问题:光标位置。

从头开始

$('div').on('keyup', function () {

    var search   = $(this),
        pattern  = /(SELECT|FROM|WHERE|DELETE)/gi,
        result   = search.text().replace(pattern, '<span class="sql">$1</span>');



    $(this).html(result);

    $('p').html(result);


});

我的小提琴:https://jsfiddle.net/yoxkjouf/

如何解决此问题

1 个答案:

答案 0 :(得分:1)

1-您没有p代码

2- $(this).html没有意义。 Cuz,它是一个输入框

&#13;
&#13;
$('div').on('keyup', function () {

    var search   = $(this),
        pattern  = /(SELECT|FROM|WHERE|DELETE)/gi,
        result   = search.text().replace(pattern, '<span class="sql">$1</span>');

  $('p').html(result);

});
&#13;
body {
    margin: 50px auto 0;
    width: 500px;
    font-family: sans-serif;
    background-color: #f1f1f1
}
[contenteditable]:empty:before {
    content: attr(data-placeholder);
    font-size: 15px;
    color: #a4a4a4;
    cursor: text;
}
[contenteditable]:focus:before {
    visibility: hidden
}
p {
    color: #fff;
    padding: 10px;
    background-color: #000;
    height: 150px
}
.sql {
    color: #4CAF50
}
div {
    border: 1px solid #ccc;
    background-color: #000;
    color: #fff;
    padding: 10px
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Type: SELECT or DELETE</h2>
<div contenteditable="true" data-placeholder="Type text"></div>
<p>
</p>
&#13;
&#13;
&#13;