我在jQueryMobile和PhoneGap工作。
我有一个问题。当我使用PlaceHolder时;
<input name="text-6" id="text-6" value="" placeholder="Put something here" type="text"/>
它在浏览器中运行良好但在移动设备中无效。我需要在这里我需要显示占位符,直到用户在该文本框中键入内容。如果占位符没有输入任何内容,只关注该文本框,则应该可以看到占位符。这是因为用户通常在阅读下一个字段之前按下选项卡,在这种情况下,空文本已经消失,并且用户更难以知道要键入的内容。比如Twitter Login Page。 但是当我们专注于那个textBox时它会隐藏。
所以我手动实现了它。
HTML
<input type="text" id="test" value="Im a placeholder!"/>
JQuery的
var placeholder = $("#test").val();
$("#test").keydown(function() {
if (this.value == placeholder) {
this.value = '';
}
}).blur(function() {
if (this.value == '') {
this.value = placeholder;
}
});
但是当我点击textBox时;光标显示在PlaceHolder值之后。
但我需要的是Cursor应该从TextBox的开头开始。我该怎么办?
答案 0 :(得分:0)
试试这个
var placeholdervalue = $("#test").attr("value");
$("#test").focus(function(){
$(this).attr('value',"");
});
$("#test").on("blur",function(){
$(this).attr('value',placeholdervalue);
});
答案 1 :(得分:0)
正如我在上面的评论中所提到的,我会使用html5占位符属性和浏览器的后备,这不支持:
// test the support
function hasPlaceholderSupport() {
var input = document.createElement('input');
return ('placeholder' in input);
}
// and as a fallback...
if(!hasPlaceholderSupport) {
$('input[type=text]').each(function() {
var elm = $(this),
ph = $(this).attr('placehold');
if(ph) {
elm.focus(function() {
if($(this).val() == ph) {
$(this).val('');
}
}).blur(function() {
if($(this).val() == '') {
$(this).val(ph);
}
});
}
})};
您可以找到演示here。
答案 2 :(得分:0)
占位符是输入框HTMl5中的一个属性..所以最好把它作为
$("#idoftheelement").attr("placeholder","your text in placeholder");
并删除它..
$("#idoftheelement").removeAttr("placeholder");
尝试这个让我知道它是否有效.....
答案 3 :(得分:0)
工作示例:http://jsfiddle.net/Gajotres/cuKxm/
您将需要此jQuery插件:https://github.com/DrPheltRight/jquery-caret
$(document).on('pagebeforeshow', '#index', function(){
var input = $('#test');
var placeholder = $("#test").val();
$("#test").keydown(function() {
if (this.value == placeholder) {
this.value = '';
}
}).blur(function() {
if (this.value == '') {
this.value = placeholder;
}
}).focus(function() {
if (this.value == placeholder) {
input.caretToStart();
}
});
});
这一行:
input.caretToStart();
会将插入光标放在输入的起始位置,就像我的例子中一样,只有在输入值为占位符文本时才能执行此操作。
答案 4 :(得分:-1)
第二次你需要获得输入值 - 也使用.val()