我一直在使用 HTML 5 占位符,只是意识到它在 HTML5 设备之外不起作用。正如您在下面的代码中看到的,占位符始终为小写,值始终为大写。
#maphead input::-webkit-input-placeholder {
text-transform:lowercase;
}
#maphead input:-moz-placeholder {
text-transform:lowercase;
}
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" style="text-transform:uppercase;" class="capital"/>
这一切都很好,除非处理非 HTML 5 设备。为此,我使用了一些糟糕的 JavaScript。
function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("type") == "text") {
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0 || value == placeholder) {
inputs[i].value = placeholder;
inputs[i].onclick = function() {
if (this.value == this.getAttribute("placeholder")) {
this.value = "";
}
return false;
}
inputs[i].onblur = function() {
if (this.value.length < 1) {
this.value = this.getAttribute("placeholder");
$('.capital').each(function() {
var current = $(this).val();
var place = $(this).attr('placeholder');
if (current == place) {
$(this).css('text-transform','lowercase')
}
});
}
}
}
}
}
}
window.onload = function() {
activatePlaceholders();
}
首先,这个 Javascript 是腐臭的。一定有更简单的 JQuery 方法。现在,尽管上面的方法确实有效(合理),但它不会响应将占位符保留为小写并将值保留为大写,因为它使用占位符设置值。
我已经为你们准备了一把漂亮的 fiddle http://jsfiddle.net/Z9YLZ/1/
最佳答案
尝试这样的事情:
$(function() {
$('input[type="text"]').each(function () {
$(this).focus(function () {
if ($(this).attr('value') === $(this).attr('placeholder')) {
$(this).css('text-transform','lowercase');
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).attr('value') === '') {
$(this).css('text-transform','uppercase');
$(this).attr('value', $(this).attr('placeholder'));
}
}).blur();
});
});
编辑:显式声明文本转换以正确级联。
关于javascript - JQuery 占位符 HTML5 模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6154620/