我有以下 jQuery 代码(类似于 this question)在 Firefox 和 IE 中工作,但在 Chrome 和 Safari 中失败(没有错误,只是不工作)。任何解决方法的想法?
$("#souper_fancy").focus(function() { $(this).select() });
这是导致选择被取消选择的 onmouseup 事件,因此您只需要添加:
$("#souper_fancy").mouseup(function(e){
e.preventDefault();
});
$('#randomfield').focus(function(event) {
setTimeout(function() {$('#randomfield').select();}, 0);
});
这适用于 input type="text" 元素。 #souper_fancy 是什么元素?
$("#souper_fancy").focus(function() {
$(this).select();
});
只是阻止 mouseup 的默认设置会导致文本选择始终处于打开状态。 MOUSEUP 事件负责清除文本选择。但是,通过阻止其默认行为,您无法使用鼠标取消选择文本。
为避免这种情况并让文本选择再次起作用,您可以在 FOCUS 上设置一个标志,从 MOUSEUP 读取它并重置它,以便将来的 MOUSEUP 事件按预期工作。
$("#souper_fancy").focus(function() {
$(this).select();
//set flag for preventing MOUSEUP event....
$this.data("preventMouseUp", true);
});
$("#souper_fancy").mouseup(function(e) {
var preventEvent = $this.data("preventMouseUp");
//only prevent default if the flag is TRUE
if (preventEvent) {
e.preventDefault();
}
//reset flag so MOUSEUP event deselect the text
$this.data("preventMouseUp", false);
});
在对 requestAnimationFrame()
的回调中使用 setSelectionRange()
:
$(document).on('focus', '._selectTextOnFocus', (e) => {
var input = e.currentTarget;
var initialType = e.currentTarget.type;
requestAnimationFrame(() => {
// input.select() is not supported on iOS
// If setSelectionRange is use on a number input in Chrome it throws an exception,
// so here we switch to type text first.
input.type = "text";
input.setSelectionRange(0, Number.MAX_SAFE_INTEGER || 9999);
input.type = initialType;
});
});
使用 setSelectionRange()
而不是 select()
,因为 select()
在移动 Safari 中不起作用(请参阅 Programmatically selecting text in an input field on iOS devices (mobile Safari))。
在选择文本之前必须使用 requestAnimationFrame
等待,否则在 iOS 上出现键盘后元素无法正确滚动到视图中。
使用 setSelectionRange()
时,将输入类型设置为 text
很重要,否则可能会在 Chrome 上引发异常(请参阅 selectionStart/selectionEnd on input type="number" no longer allowed in Chrome)。
虽然这适用于在 IE、Firefox、Chrome、Safari 和 Opera 中选择它,但它不允许您通过在 Firefox、Chrome 和 Safari 中再次单击来编辑它。不完全确定,但我认为这可能是由于这 3 个浏览器重新发出焦点事件,即使该字段已经具有焦点,因此永远不允许您实际插入光标(因为您再次选择它),而在 IE和 Opera 它似乎没有这样做,因此焦点事件没有再次被触发,因此光标被插入。
我找到了一个更好的解决方案 in this Stack post,它没有该问题并且适用于所有浏览器。
这也应该在 chrome 中工作:
$("#souper_fancy").focus(function() {
var tempSouper = $(this);
setTimeout(function(){
tempSouper.select();
},100);
});
因为使用 setTimeout 时会出现闪烁,所以还有另一种基于事件的解决方案。这样,'focus' 事件会附加 'mouseup' 事件,并且事件处理程序会再次分离自身。
function selectAllOnFocus(e) {
if (e.type == "mouseup") { // Prevent default and detach the handler
console.debug("Mouse is up. Preventing default.");
e.preventDefault();
$(e.target).off('mouseup', selectAllOnFocus);
return;
}
$(e.target).select();
console.debug("Selecting all text");
$(e.target).on('mouseup', selectAllOnFocus);
}
然后连接第一个事件
$('.varquantity').on('focus', selectAllOnFocus);
如果有人再次遇到这个问题,我在这里得到了一个纯 JS 解决方案,它(目前)适用于所有浏览器,包括。移动的
<input type="text" value="Hello world..." onFocus="window.setTimeout(() => this.select());">
(没有 setTimeout() 它不适用于 Safari、移动 Safari 和 MS Edge)