javascript - 禁用新的 block 引用内容可编辑

标签 javascript jquery contenteditable

如果在可编辑内容上按 Enter 键,则禁用新的 block 引用 JavaScript 或 jQuery

HTML

<div id="demo" contenteditable="true">
   <p>This is a paragraph. Lorem Ipsum...</p>
   <blockquote>This is a blockquote. Enter here</blockquote>
</div>

CSS

blockquote {
    background: beige;
    padding: 10px;
    border: 2px dashed #dadada;
}

片段

blockquote {
    background: beige;
    padding: 10px;
    border: 2px dashed #dadada;
}
<div id="demo" contenteditable="true">
  <p>This is a paragraph. Lorem Ipsum...</p>
  <blockquote>This is a blockquote. Enter here</blockquote>
</div>

最佳答案

答案基于This old so ans. 。对 ans 稍作修改。

$('#demo').keypress(function(e) {
  var key = e.which;
  if (key == 13) // the enter key code
  {
    var input = document.getElementById('demo');

    if (whichTag("blockquote")) {

      document.execCommand('InsertParagraph');
      document.execCommand('Outdent');

    }
  }
});

function whichTag(tagName) {

  var sel, containerNode;
  var tagFound = false;

  tagName = tagName.toUpperCase();

  if (window.getSelection) {

    sel = window.getSelection();

    if (sel.rangeCount > 0) {
      containerNode = sel.getRangeAt(0).commonAncestorContainer;
    }

  } else if ((sel = document.selection) && sel.type != "Control") {

    containerNode = sel.createRange().parentElement();

  }

  while (containerNode) {

    if (containerNode.nodeType == 1 && containerNode.tagName == tagName) {

      tagFound = true;
      containerNode = null;

    } else {

      containerNode = containerNode.parentNode;

    }

  }

  return tagFound;
}
blockquote {
  background: beige;
  padding: 10px;
  border: 2px dashed #dadada;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo" contenteditable="true">
  <p>This is a paragraph. Lorem Ipsum...</p>
  <blockquote>This is a blockquote. Enter here</blockquote>
</div>

关于javascript - 禁用新的 block 引用内容可编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44258572/

相关文章:

javascript - 滚动到 div ajax/javascript

javascript - 你如何只用正则表达式保留数字和逗号和点(出现在数字之间)?

javascript - DOJO:延迟加载 LazyTreeGrid 中的节点 - 寻找示例代码

javascript - 在同一页面上有多个 jquery 选项卡

javascript - contenteditable 选定的文本保存和恢复

javascript - 添加 post 变量以通过 AJAX 使用 FormData() 发送表单

javascript - PHP 循环的新闻/图像 slider ,(JS) 点击重置间隔和更好的唯一 ID 格式

php - 什么是JS等价于PHP函数number_format?

javascript - 如何将 div contenteditable 从 true 更改为 false

css - Chrome 使用 :after if its content is deleted; bug? 将 <br> 添加到 contenteditable span