什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
当前回答
我的解决办法是使用暂停。看起来还行
$('input[type=text]').focus(function() {
var _this = this;
setTimeout(function() {
_this.select();
}, 10);
});
其他回答
我知道内联代码是不好的风格,但我不想把它放在.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>
jQuery不是JavaScript,在某些情况下JavaScript更容易使用。
看看这个例子:
<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>
来源:CSS Tricks, MDN
$(document).ready(function() {
$("input:text")
.focus(function () { $(this).select(); } )
.mouseup(function (e) {e.preventDefault(); });
});
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()}
/>
$('input').focus(function () {
var self = $(this);
setTimeout(function () {
self.select();
}, 1);
});
编辑:根据@DavidG的请求,我不能提供详细信息,因为我不确定为什么这样工作,但我相信这与向上或向下传播的焦点事件或任何它所做的事情有关,输入元素获得它所接收的焦点通知。设置timeout会给元素一点时间来意识到它已经这样做了。
推荐文章
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何在另一个元素之后添加一个元素?
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- 为什么优秀的UI设计对某些开发者来说如此困难?
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组