使用 jQuery 选择焦点文本在 Safari 和 Chrome 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1269722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting text on focus using jQuery not working in Safari and Chrome
提问by user140550
I have the following jQuery code (similar to this question) that works in Firefox and IE, but fails (no errors, just doesn't work) in Chrome and Safari. Any ideas for a workaround?
我有以下 jQuery 代码(类似于这个问题)在 Firefox 和 IE 中工作,但在 Chrome 和 Safari 中失败(没有错误,只是不起作用)。任何解决方法的想法?
$("#souper_fancy").focus(function() { $(this).select() });
回答by
It's the onmouseup event that is causing the selection to get unselected, so you just need to add:
这是导致选择被取消选择的 onmouseup 事件,因此您只需要添加:
$("#souper_fancy").mouseup(function(e){
e.preventDefault();
});
回答by Alex0007
$('#randomfield').focus(function(event) {
setTimeout(function() {$('#randomfield').select();}, 0);
});
回答by Joe Chung
This works fine for input type="text" elements. What kind of element is #souper_fancy?
这适用于 input type="text" 元素。#souper_fancy 是一种什么样的元素?
$("#souper_fancy").focus(function() {
$(this).select();
});
回答by ThiagoPXP
Just preventing default on mouseup causes the text selection to be ON at all times. The MOUSEUP event is responsible to clear the text selection. However, by preventing its default behaviour, you are unable to deselect the textusing the mouse.
只是防止鼠标上的默认值会导致文本选择始终处于打开状态。MOUSEUP 事件负责清除文本选择。但是,通过阻止其默认行为,您无法使用鼠标取消选择文本。
To avoid that and get the text selection to work again, you can set a flag on FOCUS, read it from MOUSEUP and reset it so future MOUSEUP events will work as expected.
为了避免这种情况并使文本选择再次工作,您可以在 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);
});
回答by user2941872
Because there is flickering when you use setTimeout, there is another event based solution. This way the 'focus' event attach the 'mouseup' event and the event handler detach itself again.
因为在使用 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);
}
Then wire the first event
然后连接第一个事件
$('.varquantity').on('focus', selectAllOnFocus);
回答by andrewh
Use setSelectionRange()
inside of a callback to requestAnimationFrame()
:
使用setSelectionRange()
回调的内部requestAnimationFrame()
:
$(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;
});
});
Use setSelectionRange()
instead of select()
since select()
doesn't work in mobile Safari (see Programmatically selecting text in an input field on iOS devices (mobile Safari)).
使用setSelectionRange()
而不是select()
因为select()
在移动 Safari 中不起作用(请参阅以编程方式在 iOS 设备上的输入字段中选择文本(移动 Safari))。
It is necessary to wait using requestAnimationFrame
before selecting the text, otherwise the element isn't correctly scrolled into view after the keyboard comes up on iOS.
requestAnimationFrame
在选择文本之前需要等待使用,否则在iOS上出现键盘后元素不会正确滚动到视图中。
When using setSelectionRange()
it is important to set the input type to text
, otherwise it may throw exceptions on Chrome (see selectionStart/selectionEnd on input type="number" no longer allowed in Chrome).
使用setSelectionRange()
时将输入类型设置为 很重要text
,否则它可能会在 Chrome 上抛出异常(请参阅selectionStart/selectionEnd on input type="number" in Chrome 不再允许)。
回答by johntrepreneur
While this works for selecting it in IE, Firefox, Chrome, Safari, and Opera, it won't let you edit it by clicking a second time in Firefox, Chrome, and Safari. Not entirely sure, but I think this may be due to those 3 browsers re-issuing a focus event even though the field already has focus thus never allowing you to actually insert the cursor (since you're selecting it again), whereas in IE and Opera it appears it isn't doing that so the focus event didn't get fired again and thus the cursor gets inserted.
虽然这适用于在 IE、Firefox、Chrome、Safari 和 Opera 中选择它,但它不会让您通过在 Firefox、Chrome 和 Safari 中再次单击来编辑它。不完全确定,但我认为这可能是由于这 3 个浏览器重新发出焦点事件,即使该字段已经具有焦点,因此从不允许您实际插入光标(因为您再次选择它),而在 IE 中和 Opera 似乎没有这样做,所以焦点事件没有再次被触发,因此光标被插入。
I found a better fix in this Stack postthat doesn't have that problem and works in all browsers.
我在这篇 Stack 帖子中找到了一个更好的修复方法,它没有这个问题并且适用于所有浏览器。
回答by rubiwachs
This should work also in chrome:
这也适用于 chrome:
$("#souper_fancy").focus(function() {
var tempSouper = $(this);
setTimeout(function(){
tempSouper.select();
},100);
});
回答by Claudio
If anyone comes again across this problem I got here a pure JS solution which is (at the moment) working on all browsers incl. mobile
如果有人再次遇到这个问题,我会得到一个纯 JS 解决方案,它(目前)适用于所有浏览器,包括。移动的
<input type="text" value="Hello world..." onFocus="window.setTimeout(() => this.select());">
(without setTimeout() it's not working on Safari, mobile Safari and MS Edge)
(没有 setTimeout() 它不适用于 Safari、移动 Safari 和 MS Edge)