- placeholder, ::placeholder и :placeholder-shown
- Стилизация: изменить цвет placeholder CSS
- Поменять стиль поля ввода с placeholder CSS
- Подсказка пропадает при получении фокуса и
- В конце длинного обрезанного подсказывающего текста поставить многоточие
- Древний метод на память, изменяющий value JavaScript
- Form Input Placeholder Text
- jQuery Solution
- Pure Javascript Solution
- One Response
- Post Your Comment Cancel reply
- Popular posts
- Javascript Reference — HTML DOM Input Text placeholder Property
- Browser Support
- Syntax
- Property Values
- Return Value
- Example
- Example 2
placeholder, ::placeholder и :placeholder-shown
Стремясь уменьшить форму и сократить визуальный шум, дизайнеры тег заменяют на атрибут placeholder , тем самым увеличивая нагрузку на кратковременную память. Людям с нарушенным зрением подсказку трудно прочитать. Лучше разместить непосредственно над полем ввода. Пустое поле легче распознаётся как элемент, требующий заполнения. [uxdesign.cc]
Стилизация: изменить цвет placeholder CSS
Псевдоэлемент ::placeholder CSS определяет внешний вид подсказки из атрибута placeholder . Список поддерживаемых свойств ограничен тем же списком, что псевдоэлемент ::first-line [csswg.org] и на текущий день не включает плавный переход transition .
Поменять стиль поля ввода с placeholder CSS
Селектор [placeholder] определяет внешний вид элементов, у которых задан атрибут placeholder .
Псевдокласс :placeholder-shown CSS определяет внешний вид поля, пока видна подсказка из атрибута placeholder .
Подсказка пропадает при получении фокуса и
В конце длинного обрезанного подсказывающего текста поставить многоточие
placeholder="name@site.ru ">
Текст в плейсхолдер должен быть коротким, иначе он не имеет смысла, так как его никто не сможет увидеть.
Сделать смещающиеся или всплывающие в
.raz < position: relative; >.raz span < position: absolute; bottom: 0; left: 2px; opacity: .5; visibility: hidden; transition: .2s; >.raz input:placeholder-shown ~ span < visibility: visible; >.raz input:placeholder-shown:focus ~ span, .raz input:not(:placeholder-shown) ~ span
.raz < position: relative; >.raz span < position: absolute; bottom: 50%; left: 2px; opacity: 0; visibility: hidden; transition: .3s; >.raz input:not(:placeholder-shown) ~ span
Плавающие метки неоднородны с метками элементов других типов веб-формы. Их менее контрастный цвет хуже различим. [medium.com]
Эффект placeholder для
Атрибут placeholder работает только для и , даже если у других тегов указан атрибут contenteditable . [whatwg.org]
Древний метод на память, изменяющий value JavaScript
CoMiGo Games Стоит добавить тот факт, что placeholder в Мозилле и Хроме серьёзно отличаются — у Мозилки он с 50% прозрачностью, а в Хроме непрозрачный. Поэтому в Хроме они особо хреново распознаются как заглушка пустого поля. Поэтому я везде дополнительно пихаю такой вот код:
::-moz-placeholder, ::-webkit-input-placeholder, :-ms-input-placeholder
NMitra Да, мне тоже нравится полупрозрачный плейсхолдер. Только вот нужно писать разные правила с селекторами с префиксами, в которых полнейшее разночтение
::-webkit-input-placeholder < >input:-ms-input-placeholder < >input::-ms-input-placeholder < >input:-moz-placeholder < >input::-moz-placeholder < >input::placeholder
CoMiGo Games Ну, один такой блок кода всё равно можно добавить и перетерпеть этот момент 🙂 Так, конечно, в реальном мире разночтения отсутствуют только в том случае, если ты пишешь гибридное веб-приложение, которое всегда поставляется вместе со своим определённым вшитым браузером (как у меня, хо-хо))) Чтобы автоматически добавлялись всякие такие браузерные вариации, люди придумали препроцессоры CSS (которые берут файлы на своём языке и создают на их основе CSS) и постпроцессоры (которые работают на основе простого CSS и делают его ещё круче). Из последних известен PostCSS, из первых я предпочитаю Stylus. Надо во всём этом разбираться, да, но когда разберёшься и наделаешь себе шаблонов проектов — всё идёт на поток и на конфигурацию этих радостей современного интернета не обращаешь внимание 🙂 В общем, теперь, если будет свободное время, ты знаешь, на что его ещё можно потратить 😀 NMitra Это всё уже почти в прошлом: новые префиксы к свойствам браузеры не добавляют. С существующими нельзя добиться нормального отображения во всех версиях браузеров (IE6 и т.п.). Так что я просто отрубаю какой-то эффект для старых версий. Единственное, сморю, чтобы элемент был пусть не таким красивым, ровным и аккуратным, зато доступным. Например, надпись из span видна только при поддержки :placeholder-shown :
.raz span < visibility: hidden; >.raz input:placeholder-shown ~ span < visibility: visible; >.raz input:placeholder-shown:focus ~ span, .raz input:not(:placeholder-shown) ~ span
Form Input Placeholder Text
One of the new features coming in HTML5 is placeholder text for form inputs. The concept of placeholder text has been around for quite a while, and is fantastic for usability. Basically, placeholder text is text that appears inside of a form input when the page loads, but disappears when the user places the cursor in that form input.
Because HTML5 is still only partially supported, it’s still necessary to use javascript (you could conceivably use CSS to achieve most of the functions of placeholder, but most of the browsers that don’t support the HTML5 placeholder attribute also don’t support the necessary CSS to achieve this anyway). Within this article, I’m going to show you a few different options to add support for placeholder in all browsers.
To begin with, let’s take a look at how the placeholder attribute works. It’s quite simple. All you need to do is create an input that looks something like:
If you have a browser that supports the placeholder attribute, you’ll see “This is some placeholder text” in the form input whenever it’s empty. Of course, the placeholder attribute (at the time of this writing) is only supported in Chrome and Safari (no support for this attribute is currently available in Firefox, Opera or Internet Explorer), so you’ll need to do something else to get it working properly.
jQuery Solution
The easiest method is to use a jQuery plugin like placeHeld. PlaceHeld is a very nice, very easy-to-use plugin. Placeheld automatically determines whether or not the user’s browser supports the placeholder attribute. If the browser does not support it, the plugin fakes it by adding a value to the input that gets removed whenever the input receives focus. It even adds a CSS class to the input when it adds the placeholder text, so you can style your placeholder text differently from the standard input text. By default, a CSS class of “placeheld” is applied, but you can change that through the placeHeld options.
To use placeHeld, you will need to make sure that jQuery is in use on your site/page (if you’re using WordPress, it already is). If you’re not already using jQuery for other uses on your site, I would not recommend including it just for the use of this plug-in. If you are already using, it, though, this plug-in can be invaluable.
Once you’ve made sure jQuery is in place, you include the placeHeld plugin and then use some code similar to the following:
That’s all there is to it. The placeHeld plugin will automatically detect the placeholder attribute within your input and use that text as the fake placeholder in browsers that do not support that attribute.
Pure Javascript Solution
If you are not currently using jQuery, you can use standard javascript to achieve something similar (though, it’s more difficult to get it not to execute in browsers that support the placeholder attribute, so this method will execute in all browsers, regardless of their support for placeholder). To do this, you would use some script similar to the following:
One Response
Hi,
On my application, when i click on the placeholder text inside the textfield,the cursor does not appear but when I click at the end/outside the text ,the cursor appears .
div wairole=”presentation” dijit dijitReset dijitInline dijitLeft dijitTextBox” role=”presentation” widgetid=”__o3.appsearch.searchText”> Enter the username
>
Double click on the text “Enter the username” works(can type anything inside textfield).
click on the end/outside the text works.(can type anything inside textfield).
But single click on the text and type does not work.(cannot see cursor at all)
What could be the problem here?
Thanks
Post Your Comment Cancel reply
Join over 5000 developers who get updated once we post new tutorials and tips!
Popular posts
Javascript Reference — HTML DOM Input Text placeholder Property
The placeholder property sets or gets the placeholder attribute of a text field.
The placeholder attribute specifies a short hint text that describes the expected value of a text field.
Browser Support
placeholder | Yes | 10 | Yes | Yes | Yes |
Syntax
Return the placeholder property.
var v = textObject.placeholder
Set the placeholder property.
textObject.placeholder=text
Property Values
Return Value
A String type value representing a short hint that describes the expected value of the text field.
Example
The following code shows how to get the placeholder text of a text field.
!DOCTYPE html> html> body> !--from w w w. ja v a2 s .c om--> First Name: input type="text" >"myText" placeholder="Name"> button onclick="myFunction()">test p >"demo"> script> function myFunction() < var x = document.getElementById("myText").placeholder; document.getElementById("demo").innerHTML = x; >
The code above is rendered as follows:
Example 2
The following code shows how to change the placeholder text of a text field.
!DOCTYPE html> html> body> !--from w w w .j ava2 s . co m--> First Name: input type="text" >"myText" placeholder="Name"> button onclick="myFunction()">test script> function myFunction() < document.getElementById("myText").placeholder = "first name here.."; >
The code above is rendered as follows:
java2s.com | © Demo Source and Support. All rights reserved.