jQuery execCommand не работает как всплывающее окно в теге contenteditable HTML - PullRequest
0 голосов
/ 05 марта 2020

Я пытаюсь создать встроенный текстовый редактор с помощью функции jQuery execCommand. Для этого мой сегмент исходного кода ниже,

/*******************************************************************/
/********** Click: inner of contenteditable text-editor div ********/
/*******************************************************************/
$(document).ready(function(){
	$(function() {
	  $('.text-editor').on("click", function(e) {
			/******* Start: Click text to Background Change *********/
			$(".text-editor").removeClass("text-click");
			$(this).addClass("text-click");
			/******* End: Click text to Background Change *********/

			/******* START: Click text to tag contenteditable attr. *********/
			$(this).attr("contenteditable","true");
			/******* End: Click text to tag contenteditable attr. *********/

			/******* Start: Click text to Popup class *********/
			$(".text-editor").removeClass("popup");
			$(this).addClass("popup");
			/******* End: Click text to add Popup class *********/

			/******* Start: Click text to Popup Div *********/
			$(".popup-panel").remove();
			var PopupHtml = "<div class='popup-panel show' contenteditable='true'>\
			<button type='button' id='bold-text'><i class='fas fa-bold'></i></button>\
			<button type='button' id='underline-text'><i class='fas fa-underline'></i></button>\
			<button type='button' id='italic-text'><i class='fas fa-italic'></i></button>\
			</div>";

			$('.text-editor').contents().prop('designMode','off');
			$(this).contents().prop('designMode','on');

			if(!$('.popup-panel').length){
				$(this).append( PopupHtml );
			}
			/******* End: Click text to add Popup Div *********/
			e.stopPropagation()
	  }); 

	  /*******************************************************************/
	  /********** Click: outter of contenteditable text-editor div *******/
	  /*******************************************************************/
 	  $(document).on("click", function(e) {
	    if ($(e.target).is(".text-editor") === false) {
			/******* Start: Click text to Background Change *********/
			$(".text-editor").removeClass("text-click");
			/******* End: Click text to Background Change *********/

			/******* START: Click text to tag contenteditable attr. *********/
			$(".text-editor").removeAttr("contenteditable");
			/******* End: Click text to tag contenteditable attr. *********/

		  	/******* Start: Click text to remove Popup class *********/
		  	$(".text-editor").removeClass("popup");
		    /******* End: Click text to add Popup class *********/

		  	/******* Start: Click text to Popup Div *********/
		  	$('.text-editor').contents().prop('designMode','off');
		  	$(".popup-panel").remove();
		    /******* End: Click text to add Popup Div *********/
	    }
	  });


 	  $('#bold-text').on("click", function(e) {
 	  	document.execCommand('bold',false,null); 
 	  });

 	  $('#underline-text').on("click", function(e) {
 	  	document.execCommand('underline',false,null); 
 	  });

 	  $('#italic-text').on("click", function(e) {
 	  	document.execCommand('italic',false,null); 
 	  });


	});
});
.text-editor{ background-color: transparent; border: 1px solid transparent; display: block; }
.text-click{background-color: lightyellow; border: 1px dashed #ccc;}
*[contenteditable="true"] { outline: 0px solid transparent; }

ul.text-option{ margin: 0; padding: 0; }
ul.text-option li{ list-style: none; display: inline-block; }
ul.text-option li a{ padding: 5px; border: 1px solid #ccc; margin-right: 5px; }
button{ margin-right: 5px; }

/* Popup container - can be anything you want */
.popup { position: relative; /*display: inline-block;*/ cursor: pointer; -webkit-user-select: none; -moz-user-select: none;
  -ms-user-select: none; user-select: none;
}

/* The actual popup */
.popup .popup-panel {visibility: hidden;/*width: 160px;*/background-color: #555;color: #fff;text-align: center;border-radius: 6px;
padding: 8px;position: absolute;z-index: 1;bottom: 125%;left: 50%;margin-left: -80px;}

/* Popup arrow */
.popup .popup-panel::after {content: "";position: absolute;top: 100%;left: 50%;margin-left: -5px;border-width: 5px;
border-style: solid;border-color: #555 transparent transparent transparent;}

/* Toggle this class - hide and show the popup */
.popup .show {visibility: visible;-webkit-animation: fadeIn 1s;animation: fadeIn 1s;}

/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {from {opacity: 0;} to {opacity: 1;}}

@keyframes fadeIn {from {opacity: 0;}to {opacity:1 ;}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<div class="box">

		<h1 class="text-editor" contenteditable="true">First Heading Text</h1>
		<h2 class="text-editor">Second Heading Text</h2>
		<h3 class="text-editor">Third Heading Text</h3>
		<h4 class="text-editor">Forth Heading Text</h4>
		<h5 class="text-editor">Fifth Heading Text</h5>
		<p class="text-editor">This is paragraph text</p>
	</div>

Проблема заключается в том, что при выделении текста внутри тега html contenteditable и нажатии на всплывающую кнопку «Жирный шрифт» / «Подчеркнуть» / «Itali c», то текст не меняется как требование. Но это работает, если набор кнопок не всплывающий, как показано ниже

    <div class="box">
        <h1 class="text-editor" contenteditable="true">First Heading Text</h1>
        <h2 class="text-editor">Second Heading Text</h2>
        <h3 class="text-editor">Third Heading Text</h3>
        <h4 class="text-editor">Forth Heading Text</h4>
        <h5 class="text-editor">Fifth Heading Text</h5>
        <p class="text-editor">This is paragraph text</p>
    </div>

<ul class="text-option">
    <li><button type="button" id="bold-text"><i class="fas fa-bold"></i></button></li>
    <li><button type="button" id="underline-text"><i class="fas fa-underline"></i></button></li>
    <li><button type="button" id="italic-text"><i class="fas fa-italic"></i></button></li>
</ul>

Что здесь не так? Пожалуйста, кто-нибудь, помогите мне работать правильно.

1 Ответ

0 голосов
/ 05 марта 2020

"Устаревшая эта функция устарела. Хотя она может все еще работать в некоторых браузерах, ее использование не рекомендуется, поскольку ее можно удалить в любое время. Постарайтесь избегать ее использования."

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

Попробуйте вывести команду exe c return, поскольку она может вернуть false, если не поддерживается.

console.log(document.execCommand('underline',false,null))

"Когда документ HTML был переключен to designMode "Можете ли вы попробовать переключить execCommand в документе?

Далее, это не должно иметь место, но вы можете запустить execCommand из селектора jQuery, как

$(document).execCommand
...