如何在内容可编辑的div中输入内容时创建段落? [英] How to create a paragraph on enter in a contenteditable div?

查看:116
本文介绍了如何在内容可编辑的div中输入内容时创建段落?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的项目制作一个简单的编辑器,在该项目中,我需要使用contenteditable属性使用可编辑的div.我需要两个功能:

I'm making a simple editor for a project of mine, where I need to use an editable div using contenteditable property. I need two features:

  • 两次输入后自动插入小时数
  • 在Enter上创建一个段落,而不是<br>并关注它.
  • Auto insert hr after two enters
  • Create a paragraph instead of <br> on enter and focus on it.

因此,我(出于一些启发)编写了此代码,这是负责的代码的一部分:

So I wrote this (with some inspiration), this is part of the code that is responsible:

var intercept = {
    keydown: function(e)
    {
        if( e.which == 13 ){
            intercept.enterKey.call(null, e);
        }
    },

    enterKey: function(e)
    {
        var $lastElm;

        // Find the previous elm
        if (document.selection) { // IE
            $lastElm = $(document.selection.createRange().parentElement());
        } else { // everyone else
            $lastElm = $(window.getSelection().anchorNode);
        }

        // Handle enter key
        if( !e.shiftKey )
        {
            // Check if two or more paragraphs
            // are empty, so we can add an hr
            if(
                $.trim($lastElm.text()) === "" &&
                !$lastElm.prev().is('hr')
            ){
                document.execCommand('insertParagraph', false);
                $lastElm.replaceWith($('<hr>', {contenteditable: false}));
            }
            // Or just add an paragraph
            else{
                document.execCommand('insertParagraph', false, true);
            }

            e.preventDefault();
        }
    }
}

这在Chrome中工作正常,但是在Firefox中,它不会创建新的<p>元素,我认为它只是将当前文本包装在p中,这是不可能的,因为它已经在p中.因此,光标仅停留在Firefox中,并且不会创建新段落.

This works fine in Chrome, but in Firefox, it doesnt create a new <p> element, I think it just wraps the current text in a p which isn't possible because it's already in a p. So the cursor just stays there in firefox and new paragraph isn't created.

您知道如何解决此问题吗?
谢谢.

Do you have an idea how to fix this?
Thanks.

推荐答案

From Jquery you can use this method:

var html="";
var intercept = {
    keydown: function(e)
    {
        if( e.which == 13 ){
            intercept.enterKey.call(null, e);
        }
    },

    enterKey: function(e)
    {
        $("#append_id").html("");
        html+="your text";
        $("#append_id").html("<p>"+html+"</p>");
    }
}

这篇关于如何在内容可编辑的div中输入内容时创建段落?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆