我知道有很多问题有很多答案,但我的情况有点不同。我试图模仿“占位符”属性的确切行为,即-
1.文本保持原样
2.光标移动到文本的开头
3.无论是鼠标的点击拖动还是键盘的移位箭头,文本都是不可选的
4.文本在按键或粘贴上消失。
第五条显然是“这个”文本在提交时被删除。
我想我已经完成了'4‘的'1’和‘1’部分,但是第4的'2','3‘和第2部分(上粘贴)仍然是一个问题.:(
到目前为止我的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,我想用keypress绑定它,但是现在不需要做什么,因为在w3schools没有这样的事件attrubute:eventattributes.asp,尽管在MSDN上它显示:http://msdn.microsoft.com/en-us/library/ie/ms536955%28v=vs.85%29.aspx。
所以请救救我!
发布于 2012-10-28 11:12:00
我建议一种不同的方法,使用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);https://stackoverflow.com/questions/13108245
复制相似问题