单击按钮

时间:2018-06-28 15:33:00

标签: javascript jquery web-applications webproject

我正在尝试使用按钮单击和Java脚本功能在光标位置的内容框中添加内容,它正在框内添加,但是如果我在外部某处单击并再次单击按钮,则会在按钮内部添加内容。如何限制仅在内容div中添加内容的功能。以下是HTML和CSS:

var heading = '<span style="color:#0091DA; margin-bottom:30px; font-family:Arial, Helvetica, sans-serif; font-weight: bold; font-size:14px; line-height:120%;">Subheadings in Arial Bold 10.5pt (14px) light blue</span>';

function pasteHtmlAtCaret(html, selectPastedContent) {
  var sel, range;
  if (window.getSelection) {
    // IE9 and non-IE
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
      range = sel.getRangeAt(0);
      range.deleteContents();

      // Range.createContextualFragment() would be useful here but is
      // only relatively recently standardized and is not supported in
      // some browsers (IE9, for one)
      var el = document.createElement("div");
      el.innerHTML = html;
      var frag = document.createDocumentFragment(),
        node, lastNode;
      while ((node = el.firstChild)) {
        lastNode = frag.appendChild(node);
      }
      
      var firstNode = frag.firstChild;
      range.insertNode(frag);

      // Preserve the selection
      if (lastNode) {
        range = range.cloneRange();
        range.setStartAfter(lastNode);
        if (selectPastedContent) {
          range.setStartBefore(firstNode);
        } else {
          range.collapse(true);
        }
        
        sel.removeAllRanges();
        sel.addRange(range);
      }
    }
  } else if ((sel = document.selection) && sel.type != "Control") {
    // IE < 9
    var originalRange = sel.createRange();
    originalRange.collapse(true);
    if (document.getElementById('edit-content')[0].getAttribute("contenteditable", "true")) {
      sel.createRange().pasteHTML(html);
    }
  }
}
.main {
  border: 1px solid #000;
  width: 500px;
  height: 500px;
}

.content {
  border: 1px solid #f00;
  width: 300px;
  height: 100px;
  margin: 180px auto;
  position: relative;
}
<div class="main">
  <div class="content" id="edit-content" contenteditable="true">
    Type your text here
  </div>
</div>

<button class="temp-title" id="add_heading1" onclick="pasteHtmlAtCaret(heading);">Heading</button>

0 个答案:

没有答案