【问题标题】:JavaScript contenteditableJavaScript 内容可编辑
【发布时间】:2013-05-15 20:46:24
【问题描述】:

我正在创建一个 HTML 富文本编辑器,我想在 div 上使用 contenteditable 属性。我在一个名为编辑器的 div 中有一个 div 列表。当用户按回车键时,我会阻止默认操作。然后我在当前 div 之后插入一个新 div。唯一的问题是我不能专注于新的 div。有谁知道怎么做?

HTML

<body>
        <div id="editor" contenteditable="true">
            <div id="1" contenteditable="ture" class="line" style="height: 20px; background-color: #a0f;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #abf;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #a9f;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #aff;"></div>
            <div contenteditable="ture" class="line" style="height: 20px; background-color: #aaf;"></div>
        </div>
    </body>

JavaScript

 $(function(){

        var thisLine;

        $("#editor").bind("keydown", function(event){
            if(event.keyCode == 13){
                event.preventDefault(); 
                var newLine = $("<div tabindex=\"-1\" contenteditable=\"ture\" id=\"2\"class=\"line\" style=\"height: 20px; background-color: #aff;\"></div>");
                        newLine.insertAfter(thisLine);
                        $("#2").focus();
                    }
                })

                $(".line").bind("click", function(){
                    thisLine = $(this);
                })

            });

【问题讨论】:

  • 另外,在您的示例中,所有 div 的内部编辑器都有 contenteditable="ture" .. 这应该说 TRUE :)

标签: javascript contenteditable


【解决方案1】:

这应该可行:

newLine.insertAfter(thisLine).focus();

演示:http://jsfiddle.net/tymeJV/7xEXt/

【讨论】:

  • 所以当新插入的 div 在父 div 中时,这不起作用。
【解决方案2】:

获取所选内容,并向其中添加一个新的折叠范围。参见示例中的moveCaretToStartOf方法

function moveCaretToStartOf(element) {
  var selection = document.getSelection();
  selection.removeAllRanges();
  var range = document.createRange();
  range.setStart(element, 0);
  selection.addRange(range)
}

document.querySelector('div').focus();
window.setTimeout(function () {
	moveCaretToStartOf(document.querySelectorAll('p')[1])
}, 1000);
<blockquote>
  Cursor will be placed into the second paragraph after 1 second
</blockquote>
<div contenteditable="true">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vel laboriosam nobis nam tempore sint adipisci, ullam perspiciatis placeat aliquid dolorem. Aliquid nisi, dicta sunt dolor qui voluptatem perferendis veniam ad!</p>
  <p><br></p>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2017-06-05
    相关资源
    最近更新 更多