如何在焦点上选择textarea中的所有文本(在safari中)

我无法理解为什么当textarea获得焦点时我无法获得textarea的内容。

请访问这里的实例: http : //jsfiddle.net/mikkelbreum/aSvst/1

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

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

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

jsFiddle示例: 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); }); 

Tim Down的回答让我很接近,但是当点击并拖动Chrome时它仍然不起作用,所以我这样做了(Coffeescript)。

 $.fn.extend copyableInput: -> @.each -> $input = $(this) # Prevent the input from being edited (but allow it to be selected) $input.attr 'readonly', "readonly" if $input.is 'textarea' $input.unbind('focus').focus -> input = $(this).select() $input.data 'selected', true setTimeout -> input.select() , 0 # Work around WebKit's little problem $input.bind 'mousedown mouseup', (e) -> $input.select() if $input.data('selected') == true e.preventDefault() return false $input.unbind('blur').blur -> $input.data 'selected', false else # Select all the text when focused (I'm intentionally using click for inputs: http://stackoverflow.com/questions/3150275/jquery-input-select-all-on-focus) $input.unbind('click').click -> input = $(this).select(); setTimeout -> input.select() , 0 

这是唯一适用于Safari的东西。 焦点不起作用。

  Textarea:
Input TextBox:

焦点事件似乎干扰了select方法。 短暂滞后后调用它:

  

鉴于这只是应对,也许textarea应该是只读。

 $("textarea").on("focus", function(event) { event.preventDefault(); setTimeout(function() { $(event.target).select(); }, 1); }); 

http://jsfiddle.net/xCrN6/2/

我没有Safari浏览器,但我遇到了与IE相同的问题并在那里使用了以下工作:

 $(document).ready(function() { $('body').delegate('textarea.automarkup', 'focus', function(e) { var myText = $(this); var mytxt = myText.text(); myText.text(mytxt + "\n event fired: " + e.type); myText.select(); }); $('body').delegate('textarea.automarkup', 'click', function(e) { var myText = $(this); var mytxt = myText.text(); myText.text(mytxt + "\n event fired: " + e.type); myText.select(); }); }); 

编辑:经过一段时间的游戏,我用过:

 $(document).ready(function(e) { $(document).delegate('textarea.automarkup', 'focus click', function(e) { var myText = $(this); var mytxt = myText.text(); //myText.text(mytxt + "\n event fired: " + e.type); myText.select(); e.stopImmediatePropagation(); $('#igot').text(mytxt+e.type); return false; }); }); 

在这个例子中: http : //jsfiddle.net/MarkSchultheiss/aSvst/23/