选择使用jQuery而不是在Safari和Chrome中工作的文本。

时间:2022-11-13 19:04:33

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() });

9 个解决方案

#1


182  

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();
});

#2


24  

$('#randomfield').focus(function(event) {
    setTimeout(function() {$('#randomfield').select();}, 0);
});

#3


4  

This works fine for input type="text" elements. What kind of element is #souper_fancy?

这对于输入类型=“text”元素来说很有效。#souper_fancy是什么类型的元素?

$("#souper_fancy").focus(function() {
    $(this).select();
});

#4


2  

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上防止默认,文本选择就会一直打开。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);
});

#5


1  

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中再次单击来编辑它。不完全确定,但我认为这可能是由于这三个浏览器该证焦点事件,尽管这个领域已经有焦点因此实际上从未允许您插入光标(既然你选择一遍),而在IE和Opera似乎不是这样做所以焦点事件没有被解雇,所以光标插入。

I found a better fix in this Stack post that doesn't have that problem and works in all browsers.

我在这篇堆栈文章中找到了一个更好的解决方案,它没有这个问题,适用于所有浏览器。

#6


1  

This should work also in chrome:

这也应该在chrome中工作:

$("#souper_fancy").focus(function() {
    var tempSouper = $(this);
    setTimeout(function(){
        tempSouper.select();
    },100);
});

#7


1  

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时会闪烁,所以还有另一个基于事件的解决方案。通过这种方式,“焦点”事件附加“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);

#8


0  

Use setSelectionRange() inside of a callback to requestAnimationFrame():

在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;
    });
});

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(),因为在mobile Safari中,select()不起作用(参见在iOS设备(mobile 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上抛出异常(参见输入类型=“number”的selectionStart/selectionEnd on input type=“number”在Chrome中不再被允许)。

#9


0  

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、mobile Safari和MS Edge上工作)

#1


182  

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();
});

#2


24  

$('#randomfield').focus(function(event) {
    setTimeout(function() {$('#randomfield').select();}, 0);
});

#3


4  

This works fine for input type="text" elements. What kind of element is #souper_fancy?

这对于输入类型=“text”元素来说很有效。#souper_fancy是什么类型的元素?

$("#souper_fancy").focus(function() {
    $(this).select();
});

#4


2  

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上防止默认,文本选择就会一直打开。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);
});

#5


1  

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中再次单击来编辑它。不完全确定,但我认为这可能是由于这三个浏览器该证焦点事件,尽管这个领域已经有焦点因此实际上从未允许您插入光标(既然你选择一遍),而在IE和Opera似乎不是这样做所以焦点事件没有被解雇,所以光标插入。

I found a better fix in this Stack post that doesn't have that problem and works in all browsers.

我在这篇堆栈文章中找到了一个更好的解决方案,它没有这个问题,适用于所有浏览器。

#6


1  

This should work also in chrome:

这也应该在chrome中工作:

$("#souper_fancy").focus(function() {
    var tempSouper = $(this);
    setTimeout(function(){
        tempSouper.select();
    },100);
});

#7


1  

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时会闪烁,所以还有另一个基于事件的解决方案。通过这种方式,“焦点”事件附加“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);

#8


0  

Use setSelectionRange() inside of a callback to requestAnimationFrame():

在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;
    });
});

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(),因为在mobile Safari中,select()不起作用(参见在iOS设备(mobile 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上抛出异常(参见输入类型=“number”的selectionStart/selectionEnd on input type=“number”在Chrome中不再被允许)。

#9


0  

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、mobile Safari和MS Edge上工作)