【问题标题】:How to prevent new tags being created within a Contenteditable element?如何防止在 Contenteditable 元素中创建新标签?
【发布时间】:2017-04-02 23:21:57
【问题描述】:
<p contenteditable="true"></p>
<p contenteditable="true"></p>
<h1 contenteditable="true"></h1>

上面的代码由单独的 contenteditable 元素组成,而不是让父元素是 contenteditable。

我遇到的问题是,当用户点击任一 contenteditable 元素中的 Enter 按钮时,它会在该标签本身内创建一个新标签。

示例

输出将是:

<p contenteditable="true">
    <p>One</p>
    <p>Two</p>
</p>

期望的输出是:

<p contenteditable="true"></p>
<p contenteditable="true">One</p>
<p contenteditable="true">Two</p>

我还使用 jQuery 来确保所有元素最终都可以内容编辑:

setInterval(function () {
    $('p').attr('contenteditable','true');
    $('h1').attr('contenteditable','true');
},100);

如果有任何帮助,我将不胜感激,谢谢!

【问题讨论】:

    标签: jquery tags element contenteditable


    【解决方案1】:

    因此,您需要检测 ENTER 键以防止其换行。

    这也是触发更改元素的正确时机!

    $("[contenteditable='true']").on("keydown",function(e){
    
      if(e.which=="13"){                      // 13 is enter key
        console.log("Enter Key!!");
    
        $(this).trigger("changeElement");     // Custom event here ;)
        return false;
      }
    });
    
    // Handler for our custom event: Focus on the next!
    $("[contenteditable='true']").on("changeElement",function(){
      $(this).next().focus();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <p contenteditable="true"></p>
    <p contenteditable="true"></p>
    <h1 contenteditable="true"></h1>

    【讨论】:

    • 感谢您的回答,但它似乎禁用了回车键的使用。按下回车键后,不会在您之前所在的元素之外创建新元素。
    • 我没有看到任何应该创建新元素的东西......但是如果你把它放在“自定义事件”中,而不是“下一个焦点”,它应该可以工作。
    【解决方案2】:

    我通过检查 contenteditable 元素是否在一定时间间隔后包含p 标签来实现这一点。

    如果发生这种情况,子元素将被移到父元素前面。

    setInterval(function () {     
        $("[contenteditable='true']").each(function() {
            finder = $(this).find("p");
            $(finder).insertAfter($(this));
            $(finder).focus();
        });    
    },100);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      相关资源
      最近更新 更多