У меня небольшая проблема, атрибут placeholder
для полей ввода не поддерживается в IE 8-9.
Каков наилучший способ сделать эту поддержку в моем проекте (ASP Net). Я использую jQuery. Нужно ли использовать для этого другие внешние инструменты?
Является http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html хорошим решением?
Вы можете использовать этот плагин jQuery: https://github.com/mathiasbynens/jquery-placeholder
Но ваша ссылка, похоже, также является хорошим решением.
Вы можете использовать любое из этих полиномов:
Эти скрипты добавят поддержку атрибута placeholder
в браузерах, которые его не поддерживают, и они не требуют jQuery!
$. Browser.msie больше не находится в последнем JQuery... вы должны использовать $. support
как показано ниже:
<script>
(function ($) {
$.support.placeholder = ('placeholder' in document.createElement('input'));
})(jQuery);
//fix for IE7 and IE8
$(function () {
if (!$.support.placeholder) {
$("[placeholder]").focus(function () {
if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
}).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function () {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
});
});
}
});
</script>
У меня были проблемы с совместимостью с несколькими плагинами, которые я пробовал, это, по-моему, самый простой способ поддержки заполнителей в текстовых вводах:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
если вы используете jquery, вы можете сделать это. с этого сайта Заполнитель с JQuery
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
это альтернативные ссылки
submit
? какое отношение событие отправки имеет к чему-либо
$(function(){
if($.browser.msie && $.browser.version <= 9){
$("[placeholder]").focus(function(){
if($(this).val()==$(this).attr("placeholder")) $(this).val("");
}).blur(function(){
if($(this).val()=="") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function() {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
})
});
}
});
попробуйте это
Для других здесь посадка. Это то, что сработало для меня:
//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
Просто добавьте это в script.js файл. Предоставлено http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Я использую thisone, это только Javascript.
У меня просто есть элемент ввода со значением, и когда пользователь нажимает на элемент ввода, он меняет его на входной элемент без значения.
С помощью CSS можно легко изменить цвет текста. Цвет заполнитель - это цвет в id #IEinput, а цвет вашего напечатанного текста будет цветом в ID #email. Не используйте имя getElementsByClassName, потому что версии IE, которые не поддерживают местозаполнитель, не поддерживают getElementsByClassName либо!
Вы можете использовать заполнитель в вводе пароля, установив тип исходного ввода пароля в текст.
Tinker: http://tinker.io/4f7c5/1 - Серверы JSfiddle не работают!
* извините за мой плохой английский
JAVASCRIPT
function removeValue() {
document.getElementById('mailcontainer')
.innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
document.getElementById('email').focus(); }
HTML
<span id="mailcontainer">
<input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>
Вот функция javascript, которая создаст местозаполнители для IE 8 и ниже, и также работает для паролей:
/* Function to add placeholders to form elements on IE 8 and below */
function add_placeholders(fm) {
for (var e = 0; e < document.fm.elements.length; e++) {
if (fm.elements[e].placeholder != undefined &&
document.createElement("input").placeholder == undefined) { // IE 8 and below
fm.elements[e].style.background = "transparent";
var el = document.createElement("span");
el.innerHTML = fm.elements[e].placeholder;
el.style.position = "absolute";
el.style.padding = "2px;";
el.style.zIndex = "-1";
el.style.color = "#999999";
fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
fm.elements[e].onfocus = function() {
this.style.background = "yellow";
}
fm.elements[e].onblur = function() {
if (this.value == "") this.style.background = "transparent";
else this.style.background = "white";
}
}
}
}
add_placeholders(document.getElementById('fm'))
<form id="fm">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<textarea name="description" placeholder="Description"></textarea>
</form>
Добавьте код ниже, и это будет сделано.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
<script type="text/javascript">
// Mock client code for testing purpose
$(function(){
// Client should be able to add another change event to the textfield
$("input[name='input1']").blur(function(){ alert("Custom event triggered."); });
// Client should be able to set the field styles, without affecting place holder
$("textarea[name='input4']").css("color", "red");
// Initialize placeholder
$.Placeholder.init();
// or try initialize with parameter
//$.Placeholder.init({ color : 'rgb(255, 255, 0)' });
// call this before form submit if you are submitting by JS
//$.Placeholder.cleanBeforeSubmit();
});
</script>
Загрузите полный код и демо из https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip
<input type="text" name="Name" value="Name" onfocus="this.value = ''" onblur=" if(this.value = '') { value = 'Name'}" />
Я использовал код этой ссылки http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html
Но в браузере я использовал:
if (navigator.userAgent.indexOf('MSIE') > -1) {
//Your placeholder support code here...
}
Так как большинство решений использует jQuery или не удовлетворяет это, как мне хотелось бы, я написал фрагмент для себя для mootools.
function fix_placeholder(container){
if(container == null) container = document.body;
if(!('placeholder' in document.createElement('input'))){
var inputs = container.getElements('input');
Array.each(inputs, function(input){
var type = input.get('type');
if(type == 'text' || type == 'password'){
var placeholder = input.get('placeholder');
input.set('value', placeholder);
input.addClass('__placeholder');
if(!input.hasEvent('focus', placeholder_focus)){
input.addEvent('focus', placeholder_focus);
}
if(!input.hasEvent('blur', placeholder_blur)){
input.addEvent('blur', placeholder_blur);
}
}
});
}
}
function placeholder_focus(){
var input = $(this);
if(input.get('class').contains('__placeholder') || input.get('value') == ''){
input.removeClass('__placeholder');
input.set('value', '');
}
}
function placeholder_blur(){
var input = $(this);
if(input.get('value') == ''){
input.addClass('__placeholder');
input.set('value', input.get('placeholder'));
}
}
Я признаюсь, что он выглядит немного БОЛЕЕ, чем другие, но он отлично работает. __ placeholder - это ccs-класс, чтобы сделать цвет шрифта-заполнителя.
Я использовал fix_placeholder в window.addEvent('domready',... и для любого добавочно добавленного кода, такого как всплывающие окна.
Надеюсь, вам понравится.
С уважением.
<script>
if ($.browser.msie) {
$('input[placeholder]').each(function() {
var input = $(this);
$(input).val(input.attr('placeholder'));
$(input).focus(function() {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
$(input).blur(function() {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
;
</script>
Простое исправление!
Есть исправление с CSS, просто поместите этот код в свой файл стиля, и все заполнители будут работать правильно:
input.your-input-class: -ms-input-placeholder {
color: #000000; //Your font color
}
<input>
); атрибут - это пара ключ-значение внутри скобок (например,placeholder="This is an attribute value"
). Оставьте вопрос как есть, чтобы его могли найти будущие люди, которые задают тот же вопрос.