Идентификатор добавлен, но не удален - PullRequest
1 голос
/ 19 февраля 2020

Когда я нажимаю на кнопку с кодом <>, второй идентификатор добавляется правильно, но когда я снова нажимаю на кнопку с кодом <>, новый добавленный идентификатор не удаляется, так как я могу удалить добавленный идентификатор, так как Я пробовал некоторые альтернативы, и они не работают для меня.

Я пытаюсь удалить следующее id newID

if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
    editor.attr('id', 'editor newID');
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
    //editor.attr('id', 'editor');
    //$('div#newID').removeAttr('id');
    //editor.removeAttr( "newID" )
}

Фрагмент:

	$(function() {
		function formatHtmlCode(str) {
			var div = document.createElement('div');
			div.innerHTML = str.trim();
			return format(div, 0).innerHTML;
		}
		function format(node, level) {
			var indentBefore = new Array(level++ + 1).join('  '),
			indentAfter = new Array(level - 1).join('  '),
			textNode;
			for (var i = 0; i < node.children.length; i++) {
				textNode = document.createTextNode('\n' + indentBefore);
				node.insertBefore(textNode, node.children[i]);
				format(node.children[i], level);
				if (node.lastElementChild == node.children[i]) {
					textNode = document.createTextNode('\n' + indentAfter);
					node.appendChild(textNode);
				}
			}
			return node;
		}
		$('#editControls a').click(function(e) {
			switch ($(this).data('role')) {
				case 'p':
					document.execCommand('formatBlock', false, $(this).data('role'));
					break;
				case 'code':
					codeMode = !codeMode;
					if (codeMode) {
						var formattedHtml = formatHtmlCode(htmlDiv.html());
						htmlDiv.css("white-space", "normal"); //pre
						htmlDiv.text(formattedHtml);
						var editor = $("#editor");
						editor.addClass("black-bg-colr codeMode");
						editor.attr('id', 'editor newID');
					} else {
						htmlDiv.css("white-space", "normal");
						htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
						var editor = $("#editor");
						editor.removeClass("black-bg-colr codeMode");
						//editor.attr('id', 'editor');
            //$('div#newID').removeAttr('id');
            //editor.removeAttr( "newID" )
					}
					break;
				default:
					document.execCommand($(this).data('role'), false, null);
					break;
			}
		});

		let codeMode = false;
		let htmlDiv = $("#editor");
		htmlDiv.on('keyup', function(e) {
			if (!e.shiftKey && e.keyCode === 13) {
				document.execCommand('formatBlock', false, 'p');
			} else if (e.shiftKey) {
				document.execCommand('formatBlock', false, 'div');
			}
		});

		htmlDiv.on("paste", function(e) {
			e.preventDefault();
			var text = (e.originalEvent || e).clipboardData.getData('text/plain');
			document.execCommand('formatBlock', false, 'div');
			document.execCommand('insertText', false, text);
		});

		htmlDiv.on("input", function(e) {
			$(".editor-preview").val(htmlDiv.html());
			$(".editor-preview").keyup();
		});
		
		$('.editor-preview').keyup(function() {
			var contentAttr = $(this).attr('class');
			if (!codeMode) {
				var value = $(this).val();
				$('.' + contentAttr).html(value);
			} else {
				$('.' + contentAttr).html(htmlDiv.text());
			}
		});

	});
#editControls {
    overflow: auto;
    border-top: 1px solid transparent;
    border-left: 1px solid transparent;
    border-right: 1px solid transparent;
    border-color: silver;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    padding: .5em 1em .5em 1em;
    background-color: #fbfbfb;
    margin: 0 auto;
    width: 100%; /*90*/
}
#editor {
    resize: vertical;
    overflow: auto;
    border: 1px solid silver;
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    min-height: 100px;
    padding: 1em;
    background: white;
    margin: 0 auto;
    width: 100%;/*90*/
}
#editor:focus { 
    outline: none !important;
    box-shadow: inset 0 0 2px silver;
}
.codeMode {
    font-family:Courier New,Source Code Pro Light,Medium,Source Code Pro ExtraLight,Menlo,Consola,Monaco Linux,Consola Regular,Fira Code Regular,DejaVu Sans Mono;
    /*font-family: inherit;*/
    /*font-family: 'Courier New';*/
    border: 0px;
    font-style: inherit;
    font-variant: inherit;
    font-weight: inherit;
    font-stretch: inherit;
    line-height: inherit;
    vertical-align: baseline;
    box-sizing: inherit;
    color: #fff;
}
.black-bg-colr {
  background-color: #000 !important;
}
.btn-group {
    position: relative;
    display: inline-block;
    font-size: 0;
    vertical-align: middle;
    white-space: nowrap;
}
.btn-group+.btn-group {
    margin-left: 5px;
}
.btn-group a {
    text-decoration: none;
}
.btn-editor {
    height: 30px;
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 11px;
    font-weight: normal;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border-radius: 4px;
    border: 1px solid transparent;
    color: #333;
    background-color: #fff;
    border-color: #ccc;
}
.btn-group>.btn-editor:first-child {
    margin-left: 0;
    -webkit-border-top-left-radius: 4px;
    -moz-border-radius-topleft: 4px;
    border-top-left-radius: 4px;
    -webkit-border-bottom-left-radius: 4px;
    -moz-border-radius-bottomleft: 4px;
    border-bottom-left-radius: 4px;
}
.btn-group>.btn-editor+.btn-editor {
    margin-left: -1px !important;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.btn-not-space{
    position: relative;
    float: left;
    margin-left: 0 !important;
    border-radius: inherit;
    border: 1px solid transparent;
    border-color: #ccc;
}
.btn-editor.btn-not-space:hover {
    background-color: rgba(230, 230, 230, 0.32);
}
#preview {
    padding: 1em;
    margin: 0 auto;
    width: 97%;
    border-top: 1px dotted #c8ccd0;
    border-bottom: 1px dotted #c8ccd0;
    clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editor-wrapper">
	<div id="editControls">
		<div class="btn-group">
			<a class="btn-editor btn-not-space" data-role="bold" data-ref="#"><b>Bold</b></a>
			<a class="btn-editor btn-not-space" data-role="italic" data-ref="#"><em>Italic</em></a>
			<a class="btn-editor btn-not-space" data-role="underline" data-ref="#"><u><b>U</b></u></a>
			<a class="btn-editor btn-not-space" data-role="strikeThrough" data-ref="#"><strike>abc</strike></a>
		</div>
		<div class="btn-group">
			<a class="btn-editor btn-not-space" data-role="code" data-ref="#"><code>&lt;/&gt;</code></a>
		</div>
	</div>
  <div id="editor" contenteditable></div>
  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>
  <div id="preview" class="editor-preview"></div>
</div>

Скрипка: https://jsfiddle.net/n4ctd795/

Ответы [ 2 ]

1 голос
/ 19 февраля 2020

добавляя и удаляя классы, вы можете переключать режим кода

не нужно изменять идентификатор в любой ситуации

https://jsfiddle.net/rkv88/61xbkfto/

if (codeMode) {
    var formattedHtml = formatHtmlCode(htmlDiv.html());
    htmlDiv.css("white-space", "normal"); //pre
    htmlDiv.text(formattedHtml);
    var editor = $("#editor");
    editor.addClass("black-bg-colr codeMode");
} else {
    htmlDiv.css("white-space", "normal");
    htmlDiv.html(htmlDiv.text().replace(/\r?\n|\r/g, ""));
    var editor = $("#editor");
    editor.removeClass("black-bg-colr codeMode");
}
0 голосов
/ 20 февраля 2020

Теперь я понимаю, что вы пытаетесь сделать. Когда вы нажимаете <>, вы хотите редактировать текст в «представлении кода» ...

Итак, вот как я изменил ваш проект (без экземпляра ace. js, который касается цветовой кодировки) код):

  1. Я использую «sub div», чтобы показать код (с черным стилем фона), объявленный как переменная codeDiv.
  2. Я прямо заменяю Содержимое #editor (главный редактор) с результатом formatHtmlCode, заключенное в codeDiv.
  3. При выходе из «режима редактирования кода» я получаю содержимое codeDiv, чтобы вернуть его обратно в HTML и поместите его обратно в главный редактор. Затем я удаляю codeDiv.

Теперь здесь не используется ace.js ...
Я отредактирую это решение, когда найду, как его использовать таким образом. Это интересный вопрос;)

$(function() {

  let codeMode = false;
  let htmlDiv = $("#editor");
  htmlDiv.css("white-space", "normal"); // This could be set via CSS rule

  // Use a "sub div" to show the code
  let codeDiv = $("<div id='codeDiv' class='black-bg-colr codeMode'>")

  function formatHtmlCode(str) {
    var div = document.createElement('div');
    div.innerHTML = str.trim();
    return format(div, 0).innerHTML;
  }

  function format(node, level) {
    var indentBefore = new Array(level++ + 1).join('  '),
      indentAfter = new Array(level - 1).join('  '),
      textNode;
    for (var i = 0; i < node.children.length; i++) {
      textNode = document.createTextNode('\n' + indentBefore);
      node.insertBefore(textNode, node.children[i]);
      format(node.children[i], level);
      if (node.lastElementChild == node.children[i]) {
        textNode = document.createTextNode('\n' + indentAfter);
        node.appendChild(textNode);
      }
    }
    return node;
  }

  // HTML editor's buttons
  $('#editControls a').click(function(e) {
    switch ($(this).data('role')) {

      case 'p':
        document.execCommand('formatBlock', false, $(this).data('role'));
        break;

        // The <> code button
      case 'code':
        codeMode = !codeMode;
        if (codeMode) {

          // Format the text with the HTML tags in a "code sub div"
          var formattedHtml = formatHtmlCode(htmlDiv.html());
          codeDiv.text(formattedHtml);
          htmlDiv.html(codeDiv);
        } else {

          // Retrieve the modified HTML from the "code sub div" and overwrite the content... So the "codeDiv" is removed de facto. Simple!
          htmlDiv.html($("#codeDiv").text())
        }
        break;

      default:
        document.execCommand($(this).data('role'), false, null);
        break;
    }
  });


  htmlDiv.on('keyup', function(e) {
    if (!e.shiftKey && e.keyCode === 13) {
      document.execCommand('formatBlock', false, 'p');
    } else if (e.shiftKey) {
      document.execCommand('formatBlock', false, 'div');
    }
  });

  htmlDiv.on("paste", function(e) {
    e.preventDefault();
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');
    document.execCommand('formatBlock', false, 'div');
    document.execCommand('insertText', false, text);
  });

  htmlDiv.on("input", function(e) {
    $(".editor-preview").val(htmlDiv.html());
  });

  $('.editor-preview').keyup(function() {
    var contentAttr = $(this).attr('class');
    if (!codeMode) {
      var value = $(this).val();
      $('.' + contentAttr).html(value);
    } else {
      $('.' + contentAttr).html(htmlDiv.text());
    }
  });

});
#editControls {
  overflow: auto;
  border-top: 1px solid transparent;
  border-left: 1px solid transparent;
  border-right: 1px solid transparent;
  border-color: silver;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  padding: .5em 1em .5em 1em;
  background-color: #fbfbfb;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor {
  resize: vertical;
  overflow: auto;
  border: 1px solid silver;
  border-bottom-right-radius: 5px;
  border-bottom-left-radius: 5px;
  min-height: 100px;
  padding: 1em;
  background: white;
  margin: 0 auto;
  width: 100%;
  /*90*/
}

#editor:focus {
  outline: none !important;
  box-shadow: inset 0 0 2px silver;
}

.codeMode {
  font-family: Courier New, Source Code Pro Light, Medium, Source Code Pro ExtraLight, Menlo, Consola, Monaco Linux, Consola Regular, Fira Code Regular, DejaVu Sans Mono;
  /*font-family: inherit;*/
  /*font-family: 'Courier New';*/
  border: 0px;
  font-style: inherit;
  font-variant: inherit;
  font-weight: inherit;
  font-stretch: inherit;
  line-height: inherit;
  vertical-align: baseline;
  box-sizing: inherit;
  color: #fff;
}

.black-bg-colr {
  background-color: #000 !important;
}

.btn-group {
  position: relative;
  display: inline-block;
  font-size: 0;
  vertical-align: middle;
  white-space: nowrap;
}

.btn-group+.btn-group {
  margin-left: 5px;
}

.btn-group a {
  text-decoration: none;
}

.btn-editor {
  height: 30px;
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 11px;
  font-weight: normal;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background-image: none;
  border-radius: 4px;
  border: 1px solid transparent;
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}

.btn-group>.btn-editor:first-child {
  margin-left: 0;
  -webkit-border-top-left-radius: 4px;
  -moz-border-radius-topleft: 4px;
  border-top-left-radius: 4px;
  -webkit-border-bottom-left-radius: 4px;
  -moz-border-radius-bottomleft: 4px;
  border-bottom-left-radius: 4px;
}

.btn-group>.btn-editor+.btn-editor {
  margin-left: -1px !important;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

.btn-not-space {
  position: relative;
  float: left;
  margin-left: 0 !important;
  border-radius: inherit;
  border: 1px solid transparent;
  border-color: #ccc;
}

.btn-editor.btn-not-space:hover {
  background-color: rgba(230, 230, 230, 0.32);
}

#preview {
  padding: 1em;
  margin: 0 auto;
  width: 97%;
  border-top: 1px dotted #c8ccd0;
  border-bottom: 1px dotted #c8ccd0;
  clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="editor-wrapper">
  <div id="editControls">
    <div class="btn-group">
      <a class="btn-editor btn-not-space" data-role="bold" data-ref="#"><b>Bold</b></a>
      <a class="btn-editor btn-not-space" data-role="italic" data-ref="#"><em>Italic</em></a>
      <a class="btn-editor btn-not-space" data-role="underline" data-ref="#"><u><b>U</b></u></a>
      <a class="btn-editor btn-not-space" data-role="strikeThrough" data-ref="#"><strike>abc</strike></a>
    </div>
    <div class="btn-group">
      <a class="btn-editor btn-not-space" data-role="code" data-ref="#"><code>&lt;/&gt;</code></a>
    </div>
  </div>
  <div id="editor" contenteditable>
    <b>Hello! Use the &lt;/&gt; button to modify me.</b>
  </div>
  <textarea id="textarea" name="detail" class="editor-preview" style="display: none;"></textarea>
  <div id="preview" class="editor-preview"></div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...