HTML - Держите местозаполнитель, когда пользователь вводит
У меня есть такой ввод:
<input value="My text" placeholder="Placeholder">
Когда я печатаю что-то на входе, текст заполнителя исчезает, что совершенно очевидно.
Теперь, что я хочу сделать, так это то, что я хочу, чтобы текст заполнителя оставался, когда пользователь вводит текст, чтобы вы могли видеть текст заполнителя в качестве фонового текста за исходным текстом:
![placeholder]()
EDIT: Я также хочу иметь возможность изменять фоновый текст с помощью JavaScript.
Ответы
Ответ 1
Трудно думать о хорошем использовании для такого поведения, поскольку оно блокирует некоторых пользователей.
Простым способом было бы использовать input::after
, но это не поддерживается ни одним браузером прямо сейчас (спасибо @JukkaK.Korpela).
Но вы можете использовать элемент оболочки и атрибут данных, как показано ниже:
<div class="placeholder" data-placeholder="my placeholder">
<input value="My text" />
</div>
С помощью этого css:
.placeholder
{
position: relative;
}
.placeholder::after
{
position: absolute;
left: 5px;
top: 3px;
content: attr(data-placeholder);
pointer-events: none;
opacity: 0.6;
}
В результате: ![enter image description here]()
Нажмите здесь для демонстрации jsFiddle.
Поскольку вам нужно будет сделать много настроек, чтобы это выглядело хорошо, вы можете также рассмотреть возможность использования элемента wrapping <div>
в качестве входа "похожий":
<div class="editable" data-placeholder="my placeholder">
<input type="text" value="my Text" />
</div>
CSS
.editable
{
position: relative;
border: 1px solid gray;
padding: 3px;
background-color: white;
box-shadow: rgba(0,0,0,0.4) 2px 2px 2px inset;
}
.editable > input
{
position: relative;
z-index: 1;
border: none;
background-color: transparent;
box-shadow: none;
width: 100%;
}
.editable::after
{
position: absolute;
left: 4px;
top: 5px;
content: attr(data-placeholder);
pointer-events: none;
opacity: 0.5;
z-index: 1;
}
Нажмите здесь для демонстрации 3. (с издевательством <input />
)
Нажмите здесь для демонстрации 2. (с поддержкой контента)
Ответ 2
Значительно лучшее решение с эффектом облегчения благодаря CSS. Посмотрите: http://jsfiddle.net/csdtesting/wbqq129q/
![enter image description here]()
![enter image description here]()
Код:
#login {
font-size: 12px;
margin: 0 auto;
width: 700px;
}
#login li {
float: left;
list-style: none;
margin-left: 30px;
position: relative;
}
#login li:first-child {
margin-left: 0;
}
label {
line-height: 40px;
position: absolute;
right: 120px;
top: 0;
bottom: 0;
-moz-transition: 0.3s right ease;
-ms-transition: 0.3s right ease;
-o-transition: 0.3s right ease;
-webkit-transition: 0.3s right ease;
transition: 0.3s right ease;
z-index: 0
}
input {
color: transparent;
font-size: 12px;
height: 35px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
-moz-transition: 0.3s all ease;
-ms-transition: 0.3s all ease;
-o-transition: 0.3s all ease;
-webkit-transition: 0.3s all ease;
transition: 0.3s all ease;
}
input[type="email"],
input[type="password"] {
border: 1px solid #ccc;
height: 35px;
padding: 0 10px;
width: 240px;
position: relative;
-moz-box-shadow: inset 0 0 10px rgba(0, 0, 0, .06);
-webkit-box-shadow: inset 0 0 10px rgba(0, 0, 0, .06);
box-shadow: inset 0 0 10px rgba(0, 0, 0, .06);
z-index: 2;
}
input[type="email"] {
color: rgba(47, 130, 194, .8);
}
/* Placeholder */
input[type="email"]:-moz-placeholder {
color: rgba(47, 130, 194, .6);
}
input[type="email"]:-ms-input-placeholder {
color: rgba(47, 130, 194, .6);
}
input[type="email"]::-webkit-input-placeholder {
color: rgba(47, 130, 194, .6);
}
/* Label */
input[type="email"] + label {
color: rgb(47, 130, 194);
}
input:focus + label {
right: 10px;
}
input[type="email"]:focus,
input[type="password"]:focus {
background-color: rgba(255, 255, 255, .8);
}
/* Submit */
input[type="submit"] {
background-color: #333;
background: -moz-linear-gradient(bottom, #333, #444);
background: -ms-linear-gradient(bottom, #333, #444);
background: -o-linear-gradient(bottom, #333, #444);
background: -webkit-linear-gradient(bottom, #333, #444);
background: linear-gradient(bottom, #333, #444);
border: 1px solid #222;
color: #fff;
cursor: pointer;
height: 35px;
width: 110px;
}
<form id="login">
<ul>
<li>
<input id="email" name="email" placeholder="Your Email" title="Your Email" type="email" required />
<label for="email">Your Email</label>
</li>
</ul>
</form>
Ответ 3
Это можно сделать, используя обработчик "onchange". Вы напишете фантастическую функцию, которая будет содержать оставшуюся часть заполнителя на том, что пользователь набрал, и также поместил бы курсор в конец текста пользователя.
Вот несколько непроверенных, неполных js/psuedocode, чтобы дать вам идею:
userTextLength: 0, // measure of how many chars the user has typed; need this because the length itself won't be a valid measure, since we're modifying it in place. Note that we're using the DOM as a source of truth here... alternative method would be to store the user text itself here, but let run with this.
placeholder: "xx/yy/zz",
onchange: function() {
boxText = document.querySelector('#elem').value;
if (boxText.length === 1) { // special handling for the first character they type. (Using placeholder text at first.)
this.userTextLength++;
placeholder = boxText.slice(userTextLength);
userText = boxText.slice(0, userTextLength);
document.querySelector('#elem').innerHTML = userText + placeholder;
}
if (boxText.length < placeholder.length) { // this would mean they used backspace, which also needs to be handled.
}
else { // the normal case, should look quite similar to the first if block
this.userTextLength += 1;
userInput =
}
}
То, что я не обрабатывал здесь, - это фокусировка курсора. Для этого потребуется событие onfocus и будет использовать свойство userTextLength, чтобы решить, где его разместить. Для некоторой помощи в этом, этот ответ выглядит так, как будто это должно быть полезно.