Как сделать чтобы теги в textarea не превращались в текст?
Но если в div какой-то html код, например картинка
Отслеживать
задан 6 июн 2016 в 11:19
456 3 3 серебряных знака 17 17 бронзовых знаков
Если вам дан исчерпывающий ответ, отметьте его как верный (галка напротив выбранного ответа)
7 июн 2016 в 7:33
2 ответа 2
Сортировка: Сброс на вариант по умолчанию
Всё что находится в textarea имеет только текстовое свойство и не может содержать теги. Для этого есть div с атрибутом contenteditable=’true’
c = document.getElementById('content'); b = document.querySelectorAll('button'); b[0].onclick = function() < c.innerText = 'Font'; > b[1].onclick = function() < c.innerHTML = c.innerText; >b[2].onclick = function()
.content
Отслеживать
ответ дан 6 июн 2016 в 11:33
3,847 3 3 золотых знака 19 19 серебряных знаков 35 35 бронзовых знаков
Сделал пример codepen.io/stopani/pen/dXYRor то есть пишу в div знак < , то после нажатия на кнопку добавить этот div меняется на textarea и через инспектор видно что знак уже такой < . как сделать чтоб этот знак < не менялся?
7 июн 2016 в 10:15
@СергейЛапшин, всё что написано в div становится текстом, а не html элементом. В textarea не могут быть элементы html, только текст. Объясни толком что должно происходить?
7 июн 2016 в 10:24
Мне нужно просто отправить картинку в комментарии. Дополнил пример codepen.io/stopani/pen/dXYRor
7 июн 2016 в 10:34
@СергейЛапшин, если я правильно понял: Есть div , туда мы вставляем и после этого в div должна появиться картинка вместо текста, верно?
7 июн 2016 в 10:36
Да, но когда div меняется на textarea получается текст и картинка отправляется с ошибкой <img src=» и в комментарии уже выводится просто текстом из-за этого <
7 июн 2016 в 10:42
вы можете вставить любой текст с тегами, и этот текст прекрасно отобразится. Поэтому в скрипте должна быть выполнена следующая последовательность действий:
- Вычисляете innerHtml родительского элемента для textarea.
- Заменяете операциями над строками в нем строку между
HTML cвойства тега textarea
Textarea — один из важных элементов полей для ввода, особенно для форм обратной связи при создании сайтов. Поэтому он рождает множество проблем для верстальщиков и программистов. Есть несколько особенных HTML свойств textarea. О них я и хочу поведать.
Размеры textarea
Начнем с первых и важных свойства textarea, а именно как задать размеры (высоту и ширину) текстового поля. Для этого есть два варианта. В первом варианте задаем cols (количество символов в строке) и rows (количество строк).
Или указывать размер в CSS свойствах:
textarea
В первом случае мы точно знаем, сколько символов поместится в форме, во втором случае будет проблема, так как иногда буквы будут обрезаны.
Замещающий текст в HTML5
Существует новый атрибут в качестве части формы HTML5, называется placeholder. Это свойство textarea показывает текст приглушенно серым цветом (также работает для полей Input), который исчезает при наведении фокуса на поле или при вводе хотя бы одного символа в поле.
Работает только в современных браузерах. Есть решение для всех браузеров, оно, конечно, не будет таким красивым. Для работы необходим JS.
Обратите внимание, что значение должно быть одинаковым, иначе не будет работать.
Как убрать свечение у textarea?
Все webkit-браузеры, Firefox 3.6, все 10-е оперы навешивают голубую рамку (каемку) вокруг textarea, когда они находятся в фокусе. Вы можете удалить ее из браузера следующим образом:
textarea
Помните, что свечение textarea и полей для ввода текста является стандартом и важным элементом юзабилити сайта. Удаляя это оформление, вы создаете сложности для посетителя вашего сайта.
Как удалить маркер изменения размера у textarea?
Webkit-браузеры предлагают маленький элемент пользовательского интерфейса в правом нижнем углу textarea, при помощи которого пользователи могут изменить размеры текстового поля. Если по каким-либо причинам вы хотите удалить, то используем CSS:
textarea
Nowrap — убрать переносы
Чтобы текст автоматически не переносился, в CSS можно использовать #whatever . Но это описание не работает с textarea. Если вы хотите иметь возможность не переносить слова на новую строку в textarea, пока вы не нажмете Enter (будет возникать горизонтальная полоса прокрутки, а не срабатывает), вам придется использовать атрибут wrap=»off».
Как убрать полосу прокрутки textarea в Internet Explorer?
IE старых версий ставят вертикальную прокрутку по умолчанию на всех textarea. Вы можете спрятать его через overflow: hidden, но тогда вы не получите никакой прокрутки везде, когда текста станет больше, чем высота поля. Слава богу, overflow:auto удалит прокрутки, но включит прокрутку автоматически в случае необходимости.
JavaScript: редактируемый div
Создайте , который превращается в , если на него кликнуть.
Правильно это сформулировать надо было как-то так: «Создайте , который с точки зрения пользователя превращается в , если на него кликнуть». В программировании нет такого понятия, как «превращение», потому что программирование — это не магия.
После вышеописанного «превращения» по условиям задачи пользователь должен иметь возможность отредактировать содержимое HTML-элемента div . Окончание редактирования и обратное «превращение» HTML-элемента textarea в HTML-элемент div инициируется либо потерей фокуса HTML-элементом textarea , либо нажатием клавиши «Enter» на клавиатуре.
Что я подразумеваю под «содержимым» HTML-элемента div ? Покажу в коде на языке HTML («содержимое» отметил красным цветом):
содержимое
То есть это то, что содержится между открывающим и закрывающим тегами HTML-элемента div . «Содержимым» может быть как обычный текст, так и код на языке HTML.
Демонстрацию решения задачи, сделанную ее авторами, можно посмотреть на отдельной странице.
Кроме этого, нам дана тестовая HTML-страница (в песочнице), к которой прилагается файл my.css со стилями HTML-элементов тестовой HTML-страницы.
На заданной HTML-странице уже есть тот самый HTML-элемент div с идентификатором view , который мы будем «превращать». Очевидно, что вместо «превращения» у нас будет два разных HTML-элемента — div и textarea , между которыми мы будем переключаться: в то время, как один из этих HTML-элементов будет виден, другой будет отсутствовать (не будет виден).
Чтобы получился эффект «превращения», эти два HTML-элемента должны иметь одинаковые размеры, что и обеспечивается стилями в вышеупомянутом файле my.css . На заданной HTML-странице целевой HTML-элемент div имеет CSS-класс .view , а HTML-элемент textarea , который мы создадим в своём скрипте, будет иметь CSS-класс .edit . Оба эти CSS-класса уже описаны в файле my.css .
* * *
Приступим к решению задачи. Вышеописанное «превращение», как сказано в постановке задачи, должно запуститься, когда пользователь кликнет мышкой на целевой HTML-элемент div . То есть мы должны повесить функцию-обработчик на соответствующее событие. Пишем код:
view.addEventListener("click", function () < //. >);
В этой функции-обработчике, по идее, первым делом нужно скрыть HTML-элемент div , чтобы вместо него показать HTML-элемент textarea . Сначала я решил сделать это с помощью свойства hidden HTML-элемента div . Но это не сработало, потому что в описании CSS-класса .view HTML-элемента div есть указание display: block; , а CSS-свойство display «перебивает» (по-английски «override») HTML-свойство hidden .
Поэтому я решил действовать через установку CSS-свойства display в самом HTML-элементе (при этом оно «перебьет» это же свойство, описанное в CSS-классе .view ). Дополним код:
view.addEventListener("click", function () < // скрыть HTML-элемент div view.style.display = "none"; //. >);
Далее нам нужно создать HTML-элемент textarea (на заданной HTML-странице такого HTML-элемента нет), задать ему соответствующий CSS-класс .edit (уже описанный в файле my.css ) и передать в него «содержимое» целевого HTML-элемента div . Дополним код:
view.addEventListener("click", function () < // скрыть HTML-элемент div view.style.display = "none"; // создать HTML-элемент textarea let textarea = document.createElement("textarea"); textarea.classList.add("edit"); // CSS-класс textarea.value = view.innerHTML; // «содержимое» //. >);
Для создания эффекта «превращения» одного HTML-элемента в другой я решил вставить созданный HTML-элемент textarea после целевого HTML-элемента div . Инструкция view.style.display = «none»; не только делает HTML-элемент div невидимым, но еще заставляет браузер работать так, будто данного HTML-элемента div вообще нет на HTML-странице. Поэтому вставленный сразу после HTML-элемента div HTML-элемент textarea займет место HTML-элемента div на заданной HTML-странице. Дополним код:
view.addEventListener("click", function () < // скрыть HTML-элемент div view.style.display = "none"; // создать HTML-элемент textarea let textarea = document.createElement("textarea"); textarea.classList.add("edit"); // CSS-класс textarea.value = view.innerHTML; // «содержимое» // вставить HTML-элемент textarea после HTML-элемента div view.after(textarea); //. >);
Теперь отловим событие ухода фокуса с HTML-элемента textarea (например, это событие произойдет, если кликнуть мышкой за пределами HTML-элемента textarea ). Для этого повесим функцию-обработчик на соответствующее событие. Дополним код:
view.addEventListener("click", function () < // скрыть HTML-элемент div view.style.display = "none"; // создать HTML-элемент textarea let textarea = document.createElement("textarea"); textarea.classList.add("edit"); // CSS-класс textarea.value = view.innerHTML; // «содержимое» // вставить HTML-элемент textarea после HTML-элемента div view.after(textarea); // при уходе фокуса с HTML-элемента textarea textarea.addEventListener("blur", function () < view.innerHTML = textarea.value; // обновить содержимое HTML-элемента div textarea.remove(); // удалить HTML-элемент textarea view.style.display = ""; // убрать стиль, скрывавший HTML-элемент div >); //. >);
В этой функции-обработчике вернем отредактированное «содержимое» в HTML-элемент div , удалим теперь уже ненужный HTML-элемент textarea и сделаем HTML-элемент div видимым снова.
В принципе, это уже рабочее решение. Но по условиям задачи от нас требуется еще сделать то же самое, что при уходе фокуса с HTML-элемента textarea , и при нажатии в HTML-элементе textarea клавиши «Enter» на клавиатуре. Для этого я решил повесить функцию-обработчик на событие нажатия указанной клавиши, а в теле этой функции-обработчика вызвать метод ухода фокуса с HTML-элемента textarea . Таким образом, управление будет передано уже описанной функции-обработчику ухода фокуса. Дополним код:
view.addEventListener("click", function () < // скрыть HTML-элемент div view.style.display = "none"; // создать HTML-элемент textarea let textarea = document.createElement("textarea"); textarea.classList.add("edit"); // CSS-класс textarea.value = view.innerHTML; // «содержимое» // вставить HTML-элемент textarea после HTML-элемента div view.after(textarea); // при уходе фокуса с HTML-элемента textarea textarea.addEventListener("blur", function () < view.innerHTML = textarea.value; // обновить содержимое HTML-элемента div textarea.remove(); // удалить HTML-элемент textarea view.style.display = ""; // убрать стиль, скрывавший HTML-элемент div >); // в случае нажатия клавиши Enter делаем то же самое, что и при уходе фокуса textarea.addEventListener("keydown", function (event) < if (event.code == "Enter") textarea.blur(); >); >);
Я посчитал этот код окончательным решением задачи, но после тестирования заметил, что при щелчке мышью на HTML-элемент div не возникает курсора после его «содержимого», то есть для начала редактирования мне нужно еще щелкнуть мышью в конец «содержимого» и только потом можно начинать редактировать это «содержимое».
Чтобы избавиться от этого недостатка, я решил установить фокус программно. Дополним код ( красным цветом я пометил дополнение):
view.addEventListener("click", function () < // скрыть HTML-элемент div view.style.display = "none"; // создать HTML-элемент textarea let textarea = document.createElement("textarea"); textarea.classList.add("edit"); // CSS-класс textarea.value = view.innerHTML; // «содержимое» // вставить HTML-элемент textarea после HTML-элемента div view.after(textarea); // устанавим фокус на HTML-элемент textarea, чтобы можно было сразу набирать текст textarea.focus(); // при уходе фокуса с HTML-элемента textarea textarea.addEventListener("blur", function () < view.innerHTML = textarea.value; // обновить содержимое HTML-элемента div textarea.remove(); // удалить HTML-элемент textarea view.style.display = ""; // убрать стиль, скрывавший HTML-элемент div >); // в случае нажатия клавиши Enter делаем то же самое, что и при уходе фокуса textarea.addEventListener("keydown", function (event) < if (event.code == "Enter") textarea.blur(); >); >);
Это окончательный вариант скрипта.
Дополнение от 8 октября 2021 г. Для расширения кругозора следует упомянуть, что в языке HTML для многих HTML-элементов существует глобальный атрибут contenteditable . Например, если для HTML-элемента div указать этот атрибут со значением true , то пользователь сможет редактировать содержимое этого HTML-элемента прямо на HTML-странице, отображаемой браузером. Но, в отличие от вышеприведенного скрипта, атрибут contenteditable позволяет редактировать только текст, а не HTML-теги (то есть HTML-теги можно вставлять, но они будут вставлены именно как текст, а не как теги). Подробнее:
: The Textarea element
The HTML element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form.
Try it
The above example demonstrates a number of features of :
- An id attribute to allow the to be associated with a element for accessibility purposes
- A name attribute to set the name of the associated data point submitted to the server when the form is submitted.
- rows and cols attributes to allow you to specify an exact size for the to take. Setting these is a good idea for consistency, as browser defaults can differ.
- Default content entered between the opening and closing tags. does not support the value attribute.
The element also accepts several attributes common to form s, such as autocomplete , autofocus , disabled , placeholder , readonly , and required .
Attributes
This element includes the global attributes.
This attribute indicates whether the value of the control can be automatically completed by the browser. Possible values are:
- off : The user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically complete the entry.
- on : The browser can automatically complete the value based on values that the user has entered during previous uses.
If the autocomplete attribute is not specified on a element, then the browser uses the autocomplete attribute value of the element’s form owner. The form owner is either the element that this element is a descendant of or the form element whose id is specified by the form attribute of the input element. For more information, see the autocomplete attribute in .
A string which indicates whether to activate automatic spelling correction and processing of text substitutions (if any are configured) while the user is editing this textarea . Permitted values are:
Enable automatic spelling correction and text substitutions.
Disable automatic spelling correction and text substitutions.
This Boolean attribute lets you specify that a form control should have input focus when the page loads. Only one form-associated element in a document can have this attribute specified.
The visible width of the text control, in average character widths. If it is specified, it must be a positive integer. If it is not specified, the default value is 20 .
This attribute is used to indicate the text directionality of the element contents similar to the dirname attribute of the element. For more information, see the dirname attribute.
This Boolean attribute indicates that the user cannot interact with the control. If this attribute is not specified, the control inherits its setting from the containing element, for example ; if there is no containing element when the disabled attribute is set, the control is enabled.
The form element that the element is associated with (its «form owner»). The value of the attribute must be the id of a form element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of form elements.
The maximum string length (measured in UTF-16 code units) that the user can enter. If this value isn’t specified, the user can enter an unlimited number of characters.
The minimum string length (measured in UTF-16 code units) required that the user should enter.
The name of the control.
A hint to the user of what can be entered in the control. Carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint.
Note: Placeholders should only be used to show an example of the type of data that should be entered into a form; they are not a substitute for a proper element tied to the input. See labels for a full explanation.
This Boolean attribute indicates that the user cannot modify the value of the control. Unlike the disabled attribute, the readonly attribute does not prevent the user from clicking or selecting in the control. The value of a read-only control is still submitted with the form.
This attribute specifies that the user must fill in a value before submitting a form.
The number of visible text lines for the control. If it is specified, it must be a positive integer. If it is not specified, the default value is 2.
Specifies whether the is subject to spell checking by the underlying browser/OS. The value can be:
- true : Indicates that the element needs to have its spelling and grammar checked.
- default : Indicates that the element is to act according to a default behavior, possibly based on the parent element’s own spellcheck value.
- false : Indicates that the element should not be spell checked.
Indicates how the control should wrap the value for form submission. Possible values are:
- hard : The browser automatically inserts line breaks (CR+LF) so that each line is no longer than the width of the control; the cols attribute must be specified for this to take effect
- soft : The browser ensures that all line breaks in the entered value are a CR+LF pair, but no additional line breaks are added to the value.
- off Non-standard : Like soft but changes appearance to white-space: pre so line segments exceeding cols are not wrapped and the becomes horizontally scrollable.
If this attribute is not specified, soft is its default value.
Styling with CSS
is a replaced element — it has intrinsic dimensions, like a raster image. By default, its display value is inline-block . Compared to other form elements it is relatively easy to style, with its box model, fonts, color scheme, etc. being easily manipulable using regular CSS.
Styling HTML forms provides some useful tips on styling s.
Baseline inconsistency
The HTML specification doesn’t define where the baseline of a is, so different browsers set it to different positions. For Gecko, the baseline is set on the baseline of the first line of the textarea, on another browser it may be set on the bottom of the box. Don’t use vertical-align : baseline on it; the behavior is unpredictable.
Controlling whether a textarea is resizable
In most browsers, s are resizable — you’ll notice the drag handle in the right-hand corner, which can be used to alter the size of the element on the page. This is controlled by the resize CSS property — resizing is enabled by default, but you can explicitly disable it using a resize value of none :
textarea resize: none; >
Styling valid and invalid values
Valid and invalid values of a element (e.g. those within, and outside the bounds set by minlength , maxlength , or required ) can be highlighted using the :valid and :invalid pseudo-classes. For example, to give your textarea a different border depending on whether it is valid or invalid:
textarea:invalid border: 2px dashed red; > textarea:valid border: 2px solid lime; >
Examples
Basic example
The following example shows a very simple textarea, with a set numbers of rows and columns and some default content.
textarea name="textarea" rows="10" cols="50">Write something heretextarea>
Result
Example using «minlength» and «maxlength»
This example has a minimum and maximum number of characters — of 10 and 20 respectively. Try it and see.
textarea name="textarea" rows="5" cols="30" minlength="10" maxlength="20"> Write something here… textarea>
Result
Note that minlength doesn’t stop the user from removing characters so that the number entered goes past the minimum, but it does make the value entered into the invalid. Also note that even if you have a minlength value set (3, for example), an empty is still considered valid unless you also have the required attribute set.
Example using «placeholder»
This example has a placeholder set. Notice how it disappears when you start typing into the box.
textarea name="textarea" rows="5" cols="30" placeholder="Comment text.">textarea>
Result
Note: Placeholders should only be used to show an example of the type of data that should be entered into a form; they are not a substitute for a proper element tied to the input. See labels for a full explanation.
Disabled and readonly
This example shows two s — one of which is disabled , and one of which is readonly . Have a play with both and you’ll see the difference in behavior — the disabled element is not selectable in any way (and its value is not submitted), whereas the readonly element is selectable and its contents copyable (and its value is submitted); you just can’t edit the contents.
Note: In browsers other than Firefox, such as chrome, the disabled textarea content may be selectable and copyable.
textarea name="textarea" rows="5" cols="30" disabled> I am a disabled textarea. textarea> textarea name="textarea" rows="5" cols="30" readonly> I am a read-only textarea. textarea>
Result
Technical summary
Content categories | Flow content, phrasing content, Interactive content, listed, labelable, resettable, and submittable form-associated element. |
---|---|
Permitted content | Text |
Tag omission | None, both the starting and ending tag are mandatory. |
Permitted parents | Any element that accepts phrasing content. |
Implicit ARIA role | textbox |
Permitted ARIA roles | No role permitted |
DOM interface | HTMLTextAreaElement |
Specifications
Specification |
---|
HTML Standard # the-textarea-element |
Browser compatibility
BCD tables only load in the browser
See also
Other form-related elements:
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Jul 31, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.