Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Счетчик символов, как у Twitter (https://javascript.ru/forum/dom-window/60645-schetchik-simvolov-kak-u-twitter.html)

balov_bohdan 12.01.2016 18:36

Счетчик символов, как у Twitter
 
Вложений: 1
Доброго времени суток! Пишу на JS поле ввода, как у Твиттера (прикрепляю образец). На последнем шаге столкнулся с с задачей, которую никак не могу решить: изменение фона (или цвета) лишнего текста. Пробовал так: преобразовал вводимые символы в массив, разбил их на две части (допустимую и лишнюю), выполнил преобразование второй части (лишней), конкатенировал обе части и возвращал в поле ввода. Вариант оказался неудачным из-за невозможности полноценного форматирования строки в JS.

Кто-нибудь сталкивался с подобной задачей? Буду благодарен за ответ.

laimas 12.01.2016 19:13

http://htmlbook.ru/html/attr/contenteditable

а в поле ввода никак.

jeysmook 12.01.2016 19:29

balov_bohdan,
Да тут нужно использовать разметку, вот тебе набросал, но его нужно доделывать
http://codepen.io/anon/pen/yeXGRO?editors=010

Keramet 12.01.2016 21:42

как вариант, но "не фонтан" :(
<!doctype html>
<html>
	<head>
		<meta charset="utf8">
		<title>This</title>
		<style> 
			#main {
				width: 500px;
				height: 50px;
				padding: 5px;
				border: 1px solid #c0c0c0;
				background-color: #eee;
				border-radius: 5px;
			}
			#main em {
				background-color: rgba(0,0,0,.3);
			}
		</style>
		<script>
    window.onload = function() {
		var maxLen = 10;
		var strBefore, strAfter;
		var div = document.getElementById("main");
		
		div.onkeyup  = function() {
			strBefore = this.innerText;
			if (strBefore.length > maxLen) {
				strAfter = strBefore.slice(10);
				strBefore = strBefore.substr(0, 10);
				this.innerHTML = strBefore + "<em>" + strAfter + "</em>";
				setToEnd(div);
				console.log(strBefore);
				console.log(strAfter);
				console.log(this.innerText);
				
			}
			var txt = this.innerText;
		};
		
		function setToEnd(el) {
			var range,selection;
			if(document.createRange) {			//	для всех, IE8-
				range = document.createRange();//Create a range (a range is a like the selection but invisible)
				range.selectNodeContents(el);//Select the entire contents of the element with the range
				range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
				selection = window.getSelection();//get the selection object (allows you to change selection)
				selection.removeAllRanges();//remove any selections already made
				selection.addRange(range);//make the range you have just created the visible selection
			} else if(document.selection)	{	//	для IE8-
				range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
				range.moveToElementText(el);//Select the entire contents of the element with the range
				range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
				range.select();//Select the range (make it the visible selection
			}
		}
		
	}
	</script>
	</head>
	
	<body>
		<div id='main' contenteditable="true">
	</div>
	
	</body>
</html>

balov_bohdan 16.01.2016 16:56

Большое спасибо за ответы.


Часовой пояс GMT +3, время: 03:41.