我知道有很多问题有很多答案,但是我的情况有些不同。我正在尝试效仿"占位符"属性的确切行为,即 -
1。文本保留为onfocus
2。光标移至文本的开始
3。文本是由鼠标的click-drag或键盘的Shift-arrow
无法选择的。4。文字在按键或粘贴上消失
和第5个显然是在提交时删除的"此"文本。
我认为我已经完成了'1'和'4'但'2','3'的第一部分,而第4个的第二部分(Onpaste)仍然是一个问题...(
到目前为止我的jQuery ....
$(document).ready(function(){
if(!Modernizr.input.placeholder){
$('[placeholder]').keypress(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).keyup(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).keyup();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
//move the cursor to beginning
//move the text unselectable
}
});
}
});
对于第二和第三,我尝试使用OnSelectStart,setCursorPosition,setSelectionRange等工作...但是似乎没有任何作用。对于Onpaste而言,我认为将其与键盘绑定在一起,但现在没有在W3Schools上该怎么做BCOZ,没有这样的事件:http://www.w3schools.com/tags/tags/ref_eventattributes.asp,尽管它在msdn上显示出来:://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx。
所以请帮助!
我建议一种不同的方法,使用CSS更改要在输入上显示的标签的位置,仅在JS上显示仅在IE上,使标签可见。
(function ($) {
$.fn.placeholder = function (options) {
var options = $.extend({}, $.fn.placeholder.defaults, options);
//show <label @for> for IE
if ($.browser.msie && $.browser.version < 10)
{
return this.each(function () {
var $this = $(this);
$("label[for=" + $this.attr('id') + "]").show();
//hide placeholder on focus
$this.focus(function () {
if (!$.trim($this.val())) {
$("label[for=" + $this.attr('id') + "]").hide();
};
});
//show placeholder if the input is empty
$this.blur(function () {
if (!$.trim($this.val())) {
$("label[for=" + $this.attr('id') + "]").show();
};
});
});
}
};
//expose defaults
$.fn.placeholder.defaults = {
};
})(jQuery);