我不明白为什么当文本区域接收到焦点时,我不能让文本区域的内容被选中。
请访问此处的现场示例: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();
});
发布于 2011-06-01 21:17:46
最简单的做法是将现有代码与计时器相结合,因为在WebKit中focus
事件通常太早了:
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);
});
发布于 2011-06-01 21:11:16
这是Safari中唯一可以工作的东西。专注是行不通的。
<script type="text/javascript">
function SelectAll(id)
{
document.getElementById(id).focus();
document.getElementById(id).select();
}
</script>
Textarea:<br>
<textarea rows="3" id="txtarea" onclick="SelectAll('txtarea');" onfocus="SelectAll('txtarea');" style="width:200px" >This text you can select all by clicking here </textarea>
Input TextBox:<br>
<input type="text" id="txtfld" onclick="SelectAll('txtfld');" style="width:200px" value = "This text you can select all" />
发布于 2012-12-04 05:44:47
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
https://stackoverflow.com/questions/6201278
复制相似问题