Disable new blockquote contenteditable

左心房为你撑大大i 提交于 2020-01-03 05:23:10

问题


Disable new blockquote if Enter keypress on COntentent editable javascript or 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;
}

Snippet

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>

回答1:


Ans based on This old so ans.. Slightly modified for 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>


来源:https://stackoverflow.com/questions/44258572/disable-new-blockquote-contenteditable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!