我有以下代码在 HTML 网页中显示文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含请输入用户 ID消息。但是,我发现用户需要单击 3 次才能选择所有文本(在这种情况下是Please enter the user ID)。
是否可以一键选择整个文本?
编辑:
对不起,我忘了说:我必须使用输入type="text"
我有以下代码在 HTML 网页中显示文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含请输入用户 ID消息。但是,我发现用户需要单击 3 次才能选择所有文本(在这种情况下是Please enter the user ID)。
是否可以一键选择整个文本?
编辑:
对不起,我忘了说:我必须使用输入type="text"
您可以使用这个 javascript 片段:
<input onClick="this.select();" value="Sample Text" />
但显然它不适用于移动 Safari。在这些情况下,您可以使用:
<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />
之前发布的解决方案有两个怪癖:
这是一个完整的解决方案,它选择焦点上的所有文本,但允许在焦点后选择特定的光标点。
$(function () {
var focusedElement;
$(document).on('focus', 'input', function () {
if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
focusedElement = this;
setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
});
});
Html(您必须将 onclick 属性放在您希望它在页面上工作的每个输入上)
<input type="text" value="click the input to select" onclick="this.select();"/>
或更好的选择
jQuery(这将适用于页面上的每个文本输入,无需更改您的 html):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click','input[type=text]',function(){ this.select(); });
});
</script>
我知道这是旧的,但最好的选择是现在placeholder
尽可能使用新的 HTML 属性:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
这将导致文本显示,除非输入值,从而无需选择文本或清除输入。
您可以随时使用document.execCommand
(所有主流浏览器都支持)
document.execCommand("selectall", null, false);
选择当前焦点元素中的所有文本。
2021 年更新:execCommand
现已弃用。
老实说,这可能是最好的,因为它是一个旧的 IE API,已被其他浏览器采用,而且使用起来总是有点奇怪。尽管如此,拥有一种同时适用于<input>
字段和contenteditable
元素的解决方案还是很不错的。
.select()
可能是这些天去<input>
田野的最佳方式。
对于contenteditable
,现代解决方案是使用范围 API。
注意:当您考虑时onclick="this.select()"
,在第一次单击时,将选择所有字符,之后您可能想在输入中编辑某些内容并再次单击字符,但它会再次选择所有字符。要解决此问题,您应该使用onfocus
而不是onclick
.
尝试:
onclick="this.select()"
这对我很有效。
在我看来,列出的答案是部分的。我在下面链接了两个示例,说明如何在 Angular 和 JQuery 中执行此操作。
该解决方案具有以下特点:
jQuery: http ://plnkr.co/edit/VZ0o2FJQHTmOMfSPRqpH?p=preview
$("input").blur(function() {
if ($(this).attr("data-selected-all")) {
//Remove atribute to allow select all again on focus
$(this).removeAttr("data-selected-all");
}
});
$("input").click(function() {
if (!$(this).attr("data-selected-all")) {
try {
$(this).selectionStart = 0;
$(this).selectionEnd = $(this).value.length + 1;
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
} catch (err) {
$(this).select();
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
}
}
});
角度: http ://plnkr.co/edit/llcyAf?p=preview
var app = angular.module('app', []);
//add select-all-on-click to any input to use directive
app.directive('selectAllOnClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var hasSelectedAll = false;
element.on('click', function($event) {
if (!hasSelectedAll) {
try {
//iOS, Safari, thows exception on Chrome etc
this.selectionStart = 0;
this.selectionEnd = this.value.length + 1;
hasSelectedAll = true;
} catch (err) {
//Non iOS option if not supported, e.g. Chrome
this.select();
hasSelectedAll = true;
}
}
});
//On blur reset hasSelectedAll to allow full select
element.on('blur', function($event) {
hasSelectedAll = false;
});
}
};
}]);
输入自动对焦,带有 onfocus 事件:
<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
这使您可以打开一个带有选定元素的表单。它通过使用自动对焦来点击输入,然后向自己发送一个 onfocus 事件,该事件反过来选择文本。
确实,使用onclick="this.select();"
但记住不要将它与它结合使用disabled="disabled"
- 它不会起作用,您仍然需要手动选择或多次单击才能选择。如果您希望锁定要选择的内容值,请与属性结合使用readonly
。
你可以更换
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
和:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
占位符用于替换值,因为您希望人们能够在文本框中键入,而无需多次单击或使用 ctrl + a。占位符使它不是一个值,而是顾名思义的占位符。这就是在多个在线表格中使用的内容,上面写着“此处的用户名”或“电子邮件”,当您单击它时,“电子邮件”会消失,您可以立即开始输入。
我一直在寻找纯 CSS 的解决方案,发现它适用于 iOS 浏览器(经过测试的 safari 和 chrome)。
它在桌面 chrome 上没有相同的行为,但在那里选择的痛苦并不那么大,因为作为用户,您有更多的选择(双击、ctrl-a 等):
.select-all-on-touch {
-webkit-user-select: all;
user-select: all;
}
这是 Shoban 答案的可重复使用版本:
<input type="text" id="userid" name="userid"
value="Please enter the user ID" onfocus="Clear(this);"
/>
function Clear(elem)
{
elem.value='';
}
这样您就可以为多个元素重用清晰的脚本。
这是 React 中的一个示例,但如果您愿意,可以将其转换为 vanilla JS 上的 jQuery:
class Num extends React.Component {
click = ev => {
const el = ev.currentTarget;
if(document.activeElement !== el) {
setTimeout(() => {
el.select();
}, 0);
}
}
render() {
return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
}
}
这里的技巧是使用onMouseDown
,因为在“click”事件触发时元素已经获得焦点(因此activeElement
检查将失败)。
检查是必要的activeElement
,这样他们的用户就可以将光标定位在他们想要的位置,而无需不断地重新选择整个输入。
超时是必要的,因为否则文本将被选中然后立即取消选中,因为我猜浏览器会执行光标定位检查后记。
最后,这在 Reactel = ev.currentTarget
中是必要的,因为 React 重用事件对象,并且您将在 setTimeout 触发时丢失合成事件。
您所问的确切解决方案是:
<input type="text" id="userid" name="userid" value="Please enter the user ID" onClick="this.setSelectionRange(0, this.value.length)"/>
但我想,您正试图在输入中显示“请输入用户 ID”作为占位符或提示。因此,您可以使用以下作为更有效的解决方案:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
捕获点击事件的问题是文本中的每次后续点击都会再次选择它,而用户可能希望重新定位光标。
对我有用的是声明一个变量 selectSearchTextOnClick,并将其默认设置为 true。单击处理程序检查变量是否仍然为真:如果是,则将其设置为假并执行 select()。然后我有一个模糊事件处理程序,将其设置回真。
到目前为止的结果似乎是我所期望的行为。
(编辑:我忘了说我已经尝试按照某人的建议捕获焦点事件,但这不起作用:焦点事件触发后,单击事件可以触发,立即取消选择文本)。
当 .select() 在移动平台上不起作用时,这个问题有选项:Programmatically selection text in an input field on iOS devices (mobile Safari)
像这样的HTML
<input type="text" value="click the input to select" onclick="javascript:textSelector(this)"/>
和没有绑定的javascript代码
function textSelector(ele){
$(ele).select();
}
好吧,这是 TextBox 的正常活动。
单击 1 - 设置焦点
单击 2/3(双击)- 选择文本
您可以在页面首次加载时将焦点设置在 TextBox 上,以将“选择”减少为单个双击事件。
在输入字段中使用“占位符”而不是“值”。
我认为最好通过事件来控制。这个变体看起来非常直观,也可以与 ts 一起使用:
onFocus={e => {
e.target.select();
}
如果您需要 selectAll 每次点击,那么您可以使用它:
onClick={e => {
e.target.focus();
e.target.select();
}
如果您使用的是 AngularJS,您可以使用自定义指令来轻松访问:
define(['angular'], function () {
angular.module("selectionHelper", [])
.directive('selectOnClick', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
this.select();
});
}
};
});
});
现在可以像这样使用它:
<input type="text" select-on-click ... />
该示例使用 requirejs - 因此如果使用其他内容,可以跳过第一行和最后一行。
如果有人想在页面加载时使用 jQuery(对搜索字段很友好)执行此操作,这是我的解决方案
jQuery.fn.focusAndSelect = function() {
return this.each(function() {
$(this).focus();
if (this.setSelectionRange) {
var len = $(this).val().length * 2;
this.setSelectionRange(0, len);
} else {
$(this).val($(this).val());
}
this.scrollTop = 999999;
});
};
(function ($) {
$('#input').focusAndSelect();
})(jQuery);
基于这篇文章。感谢 CSS-Tricks.com
如果您只是想在用户选择元素时替换占位符文本,那么现在使用placeholder
属性显然是最佳实践。但是,如果您想在字段获得焦点时选择所有当前值,那么@Cory House 和@Toastrackenigma 答案的组合似乎是最规范的。使用focus
和focusout
事件,以及设置/释放当前焦点元素的处理程序,并在获得焦点时全选。一个 angular2/typescript 示例如下(但转换为 vanilla js 很简单):
模板:
<input type="text" (focus)="focus()" (focusout)="focusout()" ... >
零件:
private focused = false;
public focusout = (): void => {
this.focused = false;
};
public focus = (): void => {
if(this.focused) return;
this.focused = true;
// Timeout for cross browser compatibility (Chrome)
setTimeout(() => { document.execCommand('selectall', null, false); });
};
如果你正在寻找一个纯粹的 javascript 方法,你也可以使用:
document.createRange().selectNodeContents( element );
这将选择所有文本,并且所有主要浏览器都支持。
要触发焦点选择,您只需要像这样添加事件侦听器:
document.querySelector( element ).addEventListener( 'focusin', function () {
document.createRange().selectNodeContents( this );
} );
如果你想把它内联在你的 HTML 中,那么你可以这样做:
<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />
这只是另一种选择。似乎有几种方法可以做到这一点。(这里也提到了document.execCommand("selectall"))
document.querySelector('#myElement1').addEventListener('focusin', function() {
document.createRange().selectNodeContents(this);
});
<p>Cicking inside field will not trigger the selection, but tabbing into the fields will.</p>
<label for="">JS File Example<label><br>
<input id="myElement1" value="This is some text" /><br>
<br>
<label for="">Inline example</label><br>
<input id="myElement2" value="This also is some text" onfocus="document.createRange().selectNodeContents( this );" />
在这种情况下,使用placeholder="Please enter the user ID"
代替value="Please enter the user ID"
是最好的方法,但该函数在某些情况下可能很有用。
<input>
元素已经可以监听focus
事件。我们可以直接给它添加事件监听器,而不用再去document
监听click
。
纯 JavaScript:
document.getElementById("userid").addEventListener("focus", function() {
this.select();
});
使用 JQuery:
$("#userid").on("focus", function() {
this.select();
});
您可以使用this.setSelectionRange(0, this.value.length)
而不是this.select()
取决于您的目的,但这不适用于某些输入类型,例如number
.
<input id="my_input" style="width: 400px; height: 30px;" value="some text to select">
<br>
<button id="select-bn" style="width: 100px; height: 30px; margin-top: 20px;cursor:pointer;">Select all</button>
<br><br>
OR
<br><br>
Click to copy
<br><br>
<input id="my_input_copy" style="width: 400px; height: 30px;" value="some text to select and copy">
<br>
<button id="select-bn-copy" style="width: 170px; height: 30px; margin-top: 20px;cursor:pointer;">Click copy text</button>
<script type="text/javascript">
$(document).on('click', '#select-bn', function() {
$("#my_input").select();
});
//click to select and copy to clipboard
var text_copy_bn = document.getElementById("select-bn-copy");
text_copy_bn.addEventListener('click', function(event) {
var copy_text = document.getElementById("my_input_copy");
copy_text.focus();
copy_text.select();
try {
var works = document.execCommand('copy');
var msg = works ? 'Text copied!' : 'Could not copy!';
alert(msg);
} catch (err) {
alert('Sorry, could not copy');
}
});
</script>
用这个:
var textInput = document.querySelector("input");
textInput.onclick = function() {
textInput.selectionStart = 0;
textInput.selectionEnd = textInput.value.length;
}
<input type="text">