Rich text editor needs cursor to insert table (Own text editor, no plugins used)

时间:2015-11-12 11:25:01

标签: javascript jquery html css

I am implementing my own test editor using java script. In that I need to insert table at caret position but I am not able to place the cursor always inside the editable div. Is there any option to place cursor(caret) in editor.

I have Sample Fiddle for that.

My problems are:

I am able to click inside the editable div on that time cursor is showing. But when I click on table button the cursor is hiding. So that I am appending my table at end of editable div.

Note: In all plugins they have some code for place the cursor , I am unable migrate that to my code

My wish is:

I need to show cursor(caret)on click of any button(used for text editor) and related action(like insert table) should be insert at cursor(caret) position.

$('.wysiwyg-controls a').on('click', function(e) {
  e.preventDefault();
  document.execCommand($(this).data('role'), false);
});


//# region for popover open and close

$(function(){
    $("#popoverExampleTwo").popover({
        html: true,
        content: function() {
          return $('#popoverExampleTwoHiddenContent').html();
        },
        trigger:'click',
        title: '',
        placement:'bottom'
    });
    
});    
$('html').on('click', function(e) {
  if (typeof $(e.target).data('original-title') == 'undefined' &&
     !$(e.target).parents().is('.popover.in')) {
    $('[data-original-title]').popover('hide');
      $('.popover').css('display','none');
  }
});

//# endregion for popover open and close


$(document).on("click", "#GenBtn", function() {
    generateTable();
});

function generateTable(){
	var myRows = $("#rows").val();
			var myColumns = $("#columns").val();
			//var numberPattern = /^(\(\d+\) ?)?(\d+[\- ])*\d+$/;

			if (myRows == "" || myRows == "0" ) {
				//alert("Please enter number of Rows");
				return false;
			}
			if (myColumns == "" || myColumns == "0") {
				//alert("Please enter number of Columns");
				return false;
			}
			var html = '<table class="EditableTableInTextEditor"><tbody>';
			
			for (var i = 0; i < myRows; i++) {
				html += "<tr>";
				for (var j = 0; j < myColumns; j++) {
					html += "<td>&nbsp;</td>"
				}
				html += "</tr>"
			}
			html += "</tbody></table>";
			$(".wysiwyg-content").append(html.toString());

			if ($('.popover').length > 0) {
				$('.popover').remove();
			}
}
* {
  box-sizing: border-box;
}

.wysiwyg-editor {
  display: block;
  width: 100%;
}

.wysiwyg-controls {
  display: block;
  width: 100%;
  height: 35px;
  border: 1px solid #C2CACF;
  border-bottom: none;
  border-radius: 3px 3px 0 0;
  background: #fff;
}
.wysiwyg-controls a {
  display: inline-block;
  width: 35px;
  height: 35px;
  vertical-align: top;
  line-height: 38px;
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  color: #ADB5B9;
}
.wysiwyg-controls [data-role="bold"] {
  font-weight: bold;
}
.wysiwyg-controls [data-role="italic"] {
  font-style: italic;
}
.wysiwyg-controls [data-role="underline"] {
  text-decoration: underline;
}

[class^="menu"], [class^="menu"]:before, [class^="menu"]:after {
  position: relative;
  top: 48%;
  display: block;
  width: 65%;
  height: 2px;
  margin: 0 auto;
  background: #ADB5B9;
}
[class^="menu"]:before {
  content: '';
  top: -5px;
  width: 80%;
}
[class^="menu"]:after {
  content: '';
  top: 3px;
  width: 80%;
}

.menu-left:before, .menu-left:after {
  margin-right: 4px;
}

.menu-right:before, .menu-right:after {
  margin-left: 4px;
}

.wysiwyg-content {
  max-width: 100%;
  width: 100%;
  height: auto;
  padding: 12px;
  resize: both;
  overflow: auto;
  font-family: Helvetica, sans-serif;
  font-size: 12px;
  border: 1px solid #C2CACF;
  border-radius: 0 0 3px 3px;
  background: #F2F4F6;
}

textarea{
    width:100%;
}

.EditableTableInTextEditor{
	border-collapse:collapse;
	width:80%;
	margin:5% auto;
}

.EditableTableInTextEditor td{
	padding:15px;
	border:1px solid black;
	vertical-align:middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="wysiwyg-editor">
  <div class="wysiwyg-controls">
    <a href='#' data-role='bold'>B</a>
    <a href='#' data-role='italic'>I</a>
    <a href='#' data-role='underline'>U</a>
    <a href='#' data-role='justifyleft'><i class="menu-left"></i></a>
    <a href='#' data-role='justifycenter'><i class="menu-center"></i></a>
    <a href='#' data-role='justifyright'><i class="menu-right"></i></a>
      <input type="button" id="popoverExampleTwo" value="table"/>
  </div>
  
  <div class="wysiwyg-content" contenteditable>
    <b>Let's make a statement!</b>
    <br>
    <i>This is an italicised sentence.</i>
    <br>
    <u>Very important information.</u>
  </div>
</div>
  <div id="popoverExampleTwoHiddenContent" style="display: none">

    <form id="GenerateTableForm">
      <input type="number" min="1" max="10" name="rows" id="rows" />rows
      <input type="number" min="1" max="10" name="columns" id="columns" />columns
      <input id="GenBtn" type="button" name="button" value="create table"/>
    </form>

  </div>

can any one Please help me how to work on cursor(caret) same like plugins. Thanks in advance.

2 个答案:

答案 0 :(得分:0)

对要放置光标的div使用.focus()函数。 如果div的id是&#34; doc&#34;

然后使用 document.getElementById(&#39; doc&#39;)。focus();

答案 1 :(得分:0)

这是快速静态样本小提琴。我已经使用你的函数和参考小提琴(https://jsfiddle.net/Xeoncross/4tUDk/)创建了这个。

https://jsfiddle.net/trupti11/wLj0yb35/1/

这可能会让你不知所措。

代码: JS

var insertData = "";
function pasteHtmlAtCaret(html) {
    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
            // non-standard and not supported in all browsers (IE9, for one)
            var el = document.createElement("div");
            insertData = generateTable();
            //el.innerHTML = html;
            el.innerHTML = insertData;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}

function generateTable(){
    var myRows = 2;//$("#rows").val();
            var myColumns = 2;//$("#columns").val();
            //var numberPattern = /^(\(\d+\) ?)?(\d+[\- ])*\d+$/;

            if (myRows == "" || myRows == "0" ) {
                alert("Please enter number of Rows");
                return false;
            }
            if (myColumns == "" || myColumns == "0") {
                alert("Please enter number of Columns");
                return false;
            }
            var html = '<table class="EditableTableInTextEditor"><tbody>';

            for (var i = 0; i < myRows; i++) {
                html += "<tr>";
                for (var j = 0; j < myColumns; j++) {
                    html += "<td>&nbsp;</td>"
                }
                html += "</tr>"
            }
            html += "</tbody></table>";
      return html;
            //$(".wysiwyg-content").append(html.toString());

            //if ($('.popover').length > 0) {
            //  $('.popover').remove();
            //}
}

希望这有帮助!