digitorum.ru

Как меня найти

Профиль

icq: 4415944

javascript: простой wysiwyg под современные браузеры

javascript

Нужно было что-то очень простое, легкое и настраиваемое... Поэтому пришлось писать самому .

js/wysiwyg.js

(function() {
	
	$.fn.wysiwyg = function() {
		
		// текстарея
		var textarea = $(this);
		// редактируемый фрэйм
		var iframe = $('<iframe width="100%" height="100%"></iframe>')[0];
		var framedoc = null;
		// проверяем браузер на "иешность"
		var is_msie = (/MSIE/).test(window.navigator.userAgent);
		// контрольки
		var controls = $('<div></div>');
		// список разрешенных команд на выполнение
		var allowed_commands = ['removeFormat', 'insertOrderedList', 'insertUnorderedList', 'underline', 'italic', 'bold', 'redo', 'undo', 'justifyRight', 'justifyLeft', 'justifyFull', 'justifyCenter'];
		
		// добавить изображение
		function add_image(img) {
			var html = "<img src='" + img + "'/>";
			var selection = get_selection();
			
			if(is_msie) {
				selection.pasteHTML(html);
			} else {
				selection.deleteContents();
				selection.insertNode($(html)[0]);
			}
		}
		
		// выполнить команду форматирования
		function exec_command(cmd) {
			if($.inArray(cmd, allowed_commands) != -1) {
				framedoc.execCommand(cmd, false, null);
			}
		}
		
		// получить "селекшн"
		function get_selection() {
			iframe.contentWindow.focus();
			return is_msie ? framedoc.selection.createRange() : iframe.contentWindow.getSelection().getRangeAt(0);
		}
		
		// формируем контрольки и фрэйм
		controls
			.append('<a href="#" action="undo"><</a>')
			.append('<a href="#" action="redo">></a>')
			.append('<span>|</span>')
			.append('<a href="#" action="bold">bold</a>')
			.append('<a href="#" action="italic">italic</a>')
			.append('<a href="#" action="underline">underline</a>')
			.append('<span>|</span>')
			.append('<a href="#" action="justifyLeft">left</a>')
			.append('<a href="#" action="justifyCenter">center</a>')
			.append('<a href="#" action="justifyRight">right</a>')
			.append('<a href="#" action="justifyFull">justify</a>')
			.append('<span>|</span>')
			.append('<a href="#" action="insertUnorderedList">ul</a>')
			.append('<a href="#" action="insertOrderedList">ol</a>')
			.append('<span>|</span>')
			.append('<a href="#" action="addImage">img</a>')
			.append('<span>|</span>')
			.append('<a href="#" action="removeFormat">x</a>');
		textarea
			.hide()
			.after(iframe)
			.after(controls);
		framedoc = is_msie ? iframe.contentWindow.document : iframe.contentDocument;
		framedoc.open();
		framedoc.write('<html><head></head><body>' + textarea.val() + '&nbsp;</body></html>');
		framedoc.close();
		framedoc.designMode = "on";
		
		// биндовки
		$(document).on('click', 'a[action]', function(e) {
			var action = $(this).attr('action');
			
			e.preventDefault();
			switch(action) {
				case 'addImage' :
					add_image('http://fc02.deviantart.net/fs70/f/2014/276/3/4/bloodborne_by_alchemist10-d81ehbz.png');
					break;
				default :
					exec_command(action);
					break;
			}
		});
		
	};
	
})();

 

Пример использования:

<html>
	<head>
		<script src="js/jquery-2.1.1.min.js"></script>
		<script src="js/wysiwyg.js"></script>
		<style>
			
			.wysiwyg {
				width : 500px;
				height: 200px;
			}
			
			.wysiwyg a {
				padding-right : 5px;
			}
			
			.wysiwyg span {
				padding-right : 5px;
			}
			
		</style>
	</head>
	<body>
		<div class="wysiwyg">
			<textarea name="text">
				Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
				Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
				It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. 
				It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
			</textarea>
		</div>
		<script>
			
			(function() {
				
				$('.wysiwyg > textarea').wysiwyg();
				
			})();
			
		</script>
	</body>
</html>