我怎样被格式化这样的标签:的标签,消失的时候集中
<label for="email"> Email Address *</label>
<input id="email" type="text" name="email" value="" size="18">
显示输入文本框内部,当输入元件处于对焦或完全消失?
我找到的解决方案需要我修改html代码,我不能这样做,因为它来自第三方小部件。我可以将标签显示在输入字段的顶部,但我不知道如何让它对输入字段发生的反应做出反应。
我怎样被格式化这样的标签:的标签,消失的时候集中
<label for="email"> Email Address *</label>
<input id="email" type="text" name="email" value="" size="18">
显示输入文本框内部,当输入元件处于对焦或完全消失?
我找到的解决方案需要我修改html代码,我不能这样做,因为它来自第三方小部件。我可以将标签显示在输入字段的顶部,但我不知道如何让它对输入字段发生的反应做出反应。
你想要的是一个占位符。它是一个HTML5属性,但不支持IE和旧浏览器。为了填补,有一些图书馆在那里。我用jquery.enablePlaceholder,它工作正常。
使用JQuery,您将能够轻松地隐藏/删除当前标签并使用其内容填充占位符属性(如果需要,将由插件使用该属性)。
$(document).ready(function() {
// Fetch the label and its text
var placeholderText = $("label[for='email']").text();
// Remove the unnecessary label
$("label[for='email']").remove();
// Set the placeholder attribute
// and enable the plugin for broswer not supporting it
$("#email").attr('placeholder', placeholderText).enablePlaceholder();
});
Melanie,我用你的答案,谢谢!我可以通过这种方式改进以适应任何形式的任何数量的字段'$(“form label”)。each(function(){var field = $(this).attr('for'); $( '''').attr('placeholder',$(this).text()); $(this).remove();})' – Hernan
有什么方法可以覆盖输入onFocus
函数吗?
如果为阳性,有两路:
return false;
display
属性inline
该函数。 (不推荐 )既然你不能改变的HTML结构,这里是一个普通的JavaScript实现你的目标的手段:
function placeholding(el,greyed) {
if (!el) {
// if you don't specify a DOM node, it quits
return false;
}
else {
var input = el,
/* assumes the label element is the previous element sibling
(requires a fairly up-to-date/compliant browser */
label = el.previousElementSibling,
placeholder = label.textContent,
/* specifies the color string, or uses the default, for the
color of the place-holder */
greyed = greyed || '#999';
label.style.display = 'none';
input.value = placeholder;
input.style.color = greyed;
input.onfocus = function() {
/* if the current input-value is equal to the place-holder,
removes that value. */
if (this.value == placeholder) {
this.setAttribute('data-oldvalue', this.value);
this.value = '';
}
this.style.color = '#000';
};
input.onblur = function() {
// if no new value has been set, replaces the place-holder
if (this.value == '' || this.value.length === 0) {
this.value = this.getAttribute('data-oldvalue');
this.style.color = greyed;
}
};
}
}
placeholding(document.getElementById('email'));
,它可以隐藏以前label
元素,使用其文本input
元素中的“占位符”,隐藏该位置持有者以聚焦input
,并且如果该值未更改,则再次显示占位符。
参考文献:
如果你能使用jQuery:
$("#yourForm input[type='text']").each(function(){
$(this).attr("placeholder", $(this).prev("label").text());
}
你不再需要这方面的帮助? – Melanie