Ответ 1
<input
type="text"
placeholder="enter your text"
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'enter your text'" />
Это делается автоматически для каждого браузера, кроме Chrome.
Я предполагаю, что мне нужно настроить таргетинг на Chrome.
Любые решения?
Если не с CSS, то с jQuery?
<input
type="text"
placeholder="enter your text"
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'enter your text'" />
Редактировать: Все браузеры поддерживают сейчас
input:focus::placeholder{
color:transparent;
}
Firefox 15 и IE 10+ также поддерживают это сейчас. Чтобы расширить CSS-решение Casey Chu solution:
input:focus::-webkit-input-placeholder { color:transparent; }
input:focus:-moz-placeholder { color:transparent; } /* FF 4-18 */
input:focus::-moz-placeholder { color:transparent; } /* FF 19+ */
input:focus:-ms-input-placeholder { color:transparent; } /* IE 10+ */
Вот только CSS-решение (на данный момент работает только в WebKit):
input:focus::-webkit-input-placeholder {
opacity: 0;
}
Вы пробовали заполнить attr?
<input id ="myID" type="text" placeholder="enter your text " />
-Edit -
Я вижу, попробуйте это:
$(function () {
$('#myId').data('holder', $('#myId').attr('placeholder'));
$('#myId').focusin(function () {
$(this).attr('placeholder', '');
});
$('#myId').focusout(function () {
$(this).attr('placeholder', $(this).data('holder'));
});
});
Тест: http://jsfiddle.net/mPLFf/4/
-Edit -
Собственно, поскольку для описания значения следует использовать заполнитель, а не имя ввода. Я предлагаю следующую альтернативу
HTML:
<label class="overlabel">
<span>First Name</span>
<input name="first_name" type="text" />
</label>
JavaScript:
$('.overlabel').each(function () {
var $this = $(this);
var field = $this.find('[type=text], [type=file], [type=email], [type=password], textarea');
var span = $(this).find('> span');
var onBlur = function () {
if ($.trim(field.val()) == '') {
field.val('');
span.fadeIn(100);
} else {
span.fadeTo(100, 0);
}
};
field.focus(function () {
span.fadeOut(100);
}).blur(onBlur);
onBlur();
});
css:
.overlabel {
border: 0.1em solid;
color: #aaa;
position: relative;
display: inline-block;
vertical-align: middle;
min-height: 2.2em;
}
.overlabel span {
position: absolute;
left: 0;
top: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.overlabel span, .overlabel input {
text-align: left;
font-size: 1em;
line-height: 2em;
padding: 0 0.5em;
margin: 0;
background: transparent;
-webkit-appearance: none; /* prevent ios styling */
border-width: 0;
width: 100%;
outline: 0;
}
Тест:
Основываясь на ответах @Hexodus и @Casey Chu, здесь представлено обновленное и кросс-браузерное решение, которое использует непрозрачность CSS и переходы для вытеснения текста заполнителя. Он работает для любого элемента, который может использовать заполнители, включая textarea
и теги input
.
::-webkit-input-placeholder { opacity: 1; -webkit-transition: opacity .5s; transition: opacity .5s; } /* Chrome <=56, Safari < 10 */
:-moz-placeholder { opacity: 1; -moz-transition: opacity .5s; transition: opacity .5s; } /* FF 4-18 */
::-moz-placeholder { opacity: 1; -moz-transition: opacity .5s; transition: opacity .5s; } /* FF 19-51 */
:-ms-input-placeholder { opacity: 1; -ms-transition: opacity .5s; transition: opacity .5s; } /* IE 10+ */
::placeholder { opacity: 1; transition: opacity .5s; } /* Modern Browsers */
*:focus::-webkit-input-placeholder { opacity: 0; } /* Chrome <=56, Safari < 10 */
*:focus:-moz-placeholder { opacity: 0; } /* FF 4-18 */
*:focus::-moz-placeholder { opacity: 0; } /* FF 19-50 */
*:focus:-ms-input-placeholder { opacity: 0; } /* IE 10+ */
*:focus::placeholder { opacity: 0; } /* Modern Browsers */
Изменение: обновлено для поддержки современных браузеров.
Чтобы увеличить ответ "casey-chu" и "pirate rob", здесь более совместимый с браузером способ:
/* WebKit browsers */
input:focus::-webkit-input-placeholder { color:transparent; }
/* Mozilla Firefox 4 to 18 */
input:focus:-moz-placeholder { color:transparent; }
/* Mozilla Firefox 19+ */
input:focus::-moz-placeholder { color:transparent; }
/* Internet Explorer 10+ */
input:focus:-ms-input-placeholder { color:transparent; }
Ответ Toni хороший, но я бы предпочел отказаться от ID
и явно использовать input
, таким образом, все входы с placeholder
получат поведение:
<input type="text" placeholder="your text" />
Обратите внимание, что $(function(){ });
является сокращением для $(document).ready(function(){ });
:
$(function(){
$('input').data('holder',$('input').attr('placeholder'));
$('input').focusin(function(){
$(this).attr('placeholder','');
});
$('input').focusout(function(){
$(this).attr('placeholder',$(this).data('holder'));
});
})
Мне нравится упаковывать это в пространство имен и запускать элементы с атрибутом "placeholder"...
$("[placeholder]").togglePlaceholder();
$.fn.togglePlaceholder = function() {
return this.each(function() {
$(this)
.data("holder", $(this).attr("placeholder"))
.focusin(function(){
$(this).attr('placeholder','');
})
.focusout(function(){
$(this).attr('placeholder',$(this).data('holder'));
});
});
};
Иногда вам нужна СПЕЦИФИКАЦИЯ, чтобы убедиться, что ваши стили применяются с самым сильным фактором id
Спасибо за @Rob Fletcher за его отличный ответ, в нашей компании мы использовали
Поэтому, пожалуйста, рассмотрите добавление стилей с префиксом id контейнера приложения
#app input:focus::-webkit-input-placeholder, #app textarea:focus::-webkit-input-placeholder {
color: #FFFFFF;
}
#app input:focus:-moz-placeholder, #app textarea:focus:-moz-placeholder {
color: #FFFFFF;
}
Для дальнейшего уточнения Wallace Sidhrée пример кода:
$(function()
{
$('input').focusin(function()
{
input = $(this);
input.data('place-holder-text', input.attr('placeholder'))
input.attr('placeholder', '');
});
$('input').focusout(function()
{
input = $(this);
input.attr('placeholder', input.data('place-holder-text'));
});
})
Это гарантирует, что каждый вход сохраняет правильный текст заполнителя в атрибуте данных.
Обратитесь к рабочий пример здесь, в jsFiddle.
Мне нравится подход css, приправленный переходами. В фокусе заполнитель исчезает;) Работает также и для текстовых полей.
Спасибо @Casey Chu за отличную идею.
textarea::-webkit-input-placeholder, input::-webkit-input-placeholder {
color: #fff;
opacity: 0.4;
transition: opacity 0.5s;
-webkit-transition: opacity 0.5s;
}
textarea:focus::-webkit-input-placeholder, input:focus::-webkit-input-placeholder {
opacity: 0;
}
Используя SCSS вместе с http://bourbon.io/, это решение прост, элегантен и работает во всех веб-браузерах:
input:focus {
@include placeholder() {
color: transparent;
}
}
Используйте Бурбон! Это хорошо для вас!
С Pure CSS это сработало для меня. Сделать его прозрачным, когда вводится /Focues во вход
input:focus::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: transparent !important;
}
input:focus::-moz-placeholder { /* Firefox 19+ */
color: transparent !important;
}
input:focus:-ms-input-placeholder { /* IE 10+ */
color: transparent !important;
}
input:focus:-moz-placeholder { /* Firefox 18- */
color: transparent !important;
}
Эта часть CSS работала для меня:
input:focus::-webkit-input-placeholder {
color:transparent;
}
Для чистого решения на основе CSS:
input:focus::-webkit-input-placeholder {color:transparent;}
input:focus::-moz-placeholder {color:transparent;}
input:-moz-placeholder {color:transparent;}
Примечание: Пока не поддерживается всеми поставщиками браузеров.
Ссылка: Скрыть текст заполнителя при фокусировке с помощью CSS Илья Райскин.
HTML:
<input type="text" name="name" placeholder="enter your text" id="myInput" />
JQuery
$('#myInput').focus(function(){
$(this).attr('placeholder','');
});
$('#myInput').focusout(function(){
$(this).attr('placeholder','enter your text');
});
2018> JQUERY v.3.3 РЕШЕНИЕ: Работающая глобальность для всех входных данных, textarea с заполнителем.
$(function(){
$('input, textarea').on('focus', function(){
if($(this).attr('placeholder')){
window.oldph = $(this).attr('placeholder');
$(this).attr('placeholder', ' ');
};
});
$('input, textarea').on('blur', function(){
if($(this).attr('placeholder')){
$(this).attr('placeholder', window.oldph);
};
});
});
Демо здесь: jsfiddle
Попробуйте следующее:
//auto-hide-placeholder-text-upon-focus
if(!$.browser.webkit){
$("input").each(
function(){
$(this).data('holder',$(this).attr('placeholder'));
$(this).focusin(function(){
$(this).attr('placeholder','');
});
$(this).focusout(function(){
$(this).attr('placeholder',$(this).data('holder'));
});
});
}
для ввода
input:focus::-webkit-input-placeholder { color:transparent; }
input:focus:-moz-placeholder { color:transparent; }
для textarea
textarea:focus::-webkit-input-placeholder { color:transparent; }
textarea:focus:-moz-placeholder { color:transparent; }
$("input[placeholder]").focusin(function () {
$(this).data('place-holder-text', $(this).attr('placeholder')).attr('placeholder', '');
})
.focusout(function () {
$(this).attr('placeholder', $(this).data('place-holder-text'));
});
$("input[placeholder]").each(function () {
$(this).attr("data-placeholder", this.placeholder);
$(this).bind("focus", function () {
this.placeholder = '';
});
$(this).bind("blur", function () {
this.placeholder = $(this).attr("data-placeholder");
});
});
Помимо всего вышеизложенного, у меня есть две идеи.
Вы можете добавить элемент, который имитирует palceholder. Затем, используя javascript, элемент, показывающий и скрывающий.
Но он настолько сложный, другой использует селектор брата css. Просто так:
.placeholder { position: absolute; font-size: 14px; left: 40px; top: 11px; line-height: 1; pointer-events: none; }
.send-message input:focus + .placeholder { display: none; }
попробуйте эту функцию:
+ Он скрывает PlaceHolder в фокусе и возвращает его обратно на размытие
+ Эта функция зависит от селектора-заполнителя, сначала он выбирает элементы с атрибутом placeholder, запускает функцию фокусировки, а другую - при размывании.
в фокусе: он добавляет атрибут "data-text" к элементу, который получает его значение из атрибута placeholder, затем удаляет значение атрибута placeholder.
on blur: возвращает значение placeholder и удаляет его из атрибута data-text
<input type="text" placeholder="Username" />
$('[placeholder]').focus(function() {
$(this).attr('data-text', $(this).attr('placeholder'));
$(this).attr('placeholder', '');
}).blur(function() {
$(this).attr('placeholder', $(this).attr('data-text'));
$(this).attr('data-text', '');
});
});
вы можете следить за мной очень хорошо, если вы посмотрите, что происходит за кулисами, проверив входной элемент
То же самое, что я применил в угловом 5.
я создал новую строку для хранения заполнителя
newPlaceholder:string;
то я использовал функции фокуса и размытия на поле ввода (я использую автозаполнение).
Над местозаполнителем устанавливается из машинописного текста
Две функции, которые я использую -
/* Event fired on focus to textbox*/
Focus(data) {
this.newPlaceholder = data.target.placeholder;
this.placeholder = '';
}
/* Event fired on mouse out*/
Blur(data) {
this.placeholder = this.newPlaceholder;
}
Нет необходимости использовать любой CSS или JQuery. Вы можете сделать это прямо из тега ввода HTML.
Например, в нижнем почтовом ящике текст заполнителя исчезнет после щелчка внутри, а текст появится снова, если щелкнуть снаружи.
<input type="email" placeholder="Type your email here..." onfocus="this.placeholder=''" onblur="this.placeholder='Type your email here...'">
/* Webkit */
[placeholder]:focus::-webkit-input-placeholder { opacity: 0; }
/* Firefox < 19 */
[placeholder]:focus:-moz-placeholder { opacity: 0; }
/* Firefox > 19 */
[placeholder]:focus::-moz-placeholder { opacity: 0; }
/* Internet Explorer 10 */
[placeholder]:focus:-ms-input-placeholder { opacity: 0; }