什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
当前回答
通过加入一些函数调用,我可以稍微改进Zach的回答。这个答案的问题是它完全禁用了onMouseUp,从而阻止你在文本框中点击,一旦它有焦点。
这是我的代码:
<input type="text" onfocus="this.select()" onMouseUp="javascript:TextBoxMouseUp();" onMouseDown="javascript:TextBoxMouseDown();" />
<script type="text/javascript">
var doMouseUp = true;
function TextBoxMouseDown() {
doMouseUp = this == document.activeElement;
return doMouseUp;
}
function TextBoxMouseUp() {
if (doMouseUp)
{ return true; }
else {
doMouseUp = true;
return false;
}
}
</script>
这比扎克的回答略有进步。它在IE中工作得很完美,在Chrome中完全不能工作,在FireFox中则是交替成功(几乎每隔一次)。如果有人有一个想法,如何使它可靠地工作在FF或Chrome,请分享。
总之,我想我应该分享我所能做的让这一切更美好。
其他回答
如果你把这些事件链接在一起,我相信就不需要使用.one了,就像本文其他地方建议的那样。
例子:
$('input.your_element').focus( function () {
$(this).select().mouseup( function (e) {
e.preventDefault();
});
});
我知道内联代码是不好的风格,但我不想把它放在.js文件中。 不用jQuery也能工作!
<input type="text" value="blah blah" onfocus="this.select(); this.selAll=1;" onmouseup="if(this.selAll==0) return true; this.selAll=0; return false;"></input>
$('input').focus(function () {
var self = $(this);
setTimeout(function () {
self.select();
}, 1);
});
编辑:根据@DavidG的请求,我不能提供详细信息,因为我不确定为什么这样工作,但我相信这与向上或向下传播的焦点事件或任何它所做的事情有关,输入元素获得它所接收的焦点通知。设置timeout会给元素一点时间来意识到它已经这样做了。
我的解决办法是使用暂停。看起来还行
$('input[type=text]').focus(function() {
var _this = this;
setTimeout(function() {
_this.select();
}, 10);
});
HTML:
var textFiled = document.getElementById("text-filed"); 文本文件。addEventListener("focus", function() {this.select();}); 输入你的文本:<input type=" Text " id=" Text -filed" value="test with filed Text ">
使用JQuery:
$("#text-filed").focus(function() { $(this).select(); } );
使用React JS:
在各自的组成部分-
<input
type="text"
value="test"
onFocus={e => e.target.select()}
/>
推荐文章
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式