如何使得当你点击textarea内部时,它的整个内容都被选中?
并且当你再次单击时,取消选择。
如何使得当你点击textarea内部时,它的整个内容都被选中?
并且当你再次单击时,取消选择。
<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>
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;
});
});
tab
进入文本区域,则会失败 - 你的另一个解决方案适用于两种情况 :) - zack$("#foo").mouseup(function() {
$("#foo").unbind("mouseup");
return false;
});
你需要在不使用 this
的情况下引用文本框,只需使用完整路径引用即可。这样它就能正常工作了。 - pratikabu更好的方法,解决了选项卡和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;
});
}
});
最终我使用了这个:
$('.selectAll').toggle(function() {
$(this).select();
}, function() {
$(this).unselect();
});
$('textarea').focus(function() {
this.select();
}).mouseup(function() {
return false;
});
稍微缩短了一点的jQuery版本:
$('your-element').focus(function(e) {
e.target.select();
jQuery(e.target).one('mouseup', function(e) {
e.preventDefault();
});
});
它正确处理了Chrome的特殊情况。参见http://jsfiddle.net/Ztyx/XMkwm/以获取示例。
disabled
属性在我的<textarea disabled>test</textarea>
中,但它不起作用,那么如何修复它? - mastersuse:)
使用那篇帖子上被接受的答案,你可以像这样调用函数:
$(function() {
$('#textareaId').click(function() {
SelectText('#textareaId');
});
});
$(this).select()
来实现这个功能,我会使用它,因为代码更简洁 :) - Alex