如何在焦点上选择 textarea 中的所有文本(在 safari 中) [英] how to select all text in textarea on focus (in safari)

查看:23
本文介绍了如何在焦点上选择 textarea 中的所有文本(在 safari 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么当 textarea 获得焦点时我无法获取要选择的 textarea 的内容.

I can't work out why I can't get the the content of a textarea to be selected when the textarea receives focus.

请在此处访问现场示例:http://jsfiddle.net/mikkelbreum/aSvst/1

Please visit a live example here: http://jsfiddle.net/mikkelbreum/aSvst/1

使用 jQuery,这是我的代码.(在 SAFARI 中)它在点击事件的情况下选择文本,而不是焦点事件:

Using jQuery, this is my code. (IN SAFARI) It makes the text selected in case of the click event, but not the focus event:

$('textarea.automarkup')
.mouseup(function(e){
    // fixes safari/chrome problem
    e.preventDefault();
})
.focus(function(e){
    $(this).select();
})
.click(function(e){
    $(this).select();
});

推荐答案

最简单的做法是将您现有的代码与计时器结合起来,因为 focus 事件在 WebKit 中通常为时过早:

The simplest thing to do is to combine your existing code with a timer, since the focus event is generally too early in WebKit:

jsFiddle 示例:http://jsfiddle.net/NWaav/2/

jsFiddle example: http://jsfiddle.net/NWaav/2/

代码:

$('textarea.automarkup').focus(function() {
    var $this = $(this);

    $this.select();

    window.setTimeout(function() {
        $this.select();
    }, 1);

    // Work around WebKit's little problem
    function mouseUpHandler() {
        // Prevent further mouseup intervention
        $this.off("mouseup", mouseUpHandler);
        return false;
    }

    $this.mouseup(mouseUpHandler);
});

这篇关于如何在焦点上选择 textarea 中的所有文本(在 safari 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆