Ale*_*lex 127 javascript forms jquery textarea selection
当你在textarea里面点击时,我怎么能这样做,它的整个内容都被选中了?
最后再次点击时,取消选择它.
Tim*_*own 191
为了防止用户在每次尝试使用鼠标移动插入符号时选择整个文本时会感到恼火,您应该使用focus事件而不是click事件来执行此操作.以下将完成这项工作并解决Chrome中的一个问题,该问题阻止了最简单的版本(即select()在focus事件处理程序中调用textarea的方法).
jsFiddle:http://jsfiddle.net/NM62A/
码:
<textarea id="foo">Some text</textarea>
<script type="text/javascript">
var textBox = document.getElementById("foo");
textBox.onfocus = function() {
textBox.select();
// Work around Chrome's little problem
textBox.onmouseup = function() {
// Prevent further mouseup intervention
textBox.onmouseup = null;
return false;
};
};
</script>
Run Code Online (Sandbox Code Playgroud)
jQuery版本:
$("#foo").focus(function() {
var $this = $(this);
$this.select();
// Work around Chrome's little problem
$this.mouseup(function() {
// Prevent further mouseup intervention
$this.unbind("mouseup");
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
小智 14
更好的方法,解决了tab和chrome问题以及新的jquery方式
$("#element").on("focus keyup", function(e){
var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if(keycode === 9 || !keycode){
// Hacemos select
var $this = $(this);
$this.select();
// Para Chrome's que da problema
$this.on("mouseup", function() {
// Unbindeamos el mouseup
$this.off("mouseup");
return false;
});
}
});
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 11
我最终使用了这个:
$('.selectAll').toggle(function() {
$(this).select();
}, function() {
$(this).unselect();
});
Run Code Online (Sandbox Code Playgroud)
略短的jQuery版本:
$('your-element').focus(function(e) {
e.target.select();
jQuery(e.target).one('mouseup', function(e) {
e.preventDefault();
});
});
Run Code Online (Sandbox Code Playgroud)
它正确处理Chrome角落的情况.有关示例,请参见http://jsfiddle.net/Ztyx/XMkwm/.
$('textarea').focus(function() {
this.select();
}).mouseup(function() {
return false;
});
Run Code Online (Sandbox Code Playgroud)