【问题标题】:Selecting text on focus using jQuery not working in iPhone iPad Browsers [duplicate]使用 jQuery 选择焦点上的文本在 iPhone iPad 浏览器中不起作用 [重复]
【发布时间】:2012-04-13 01:09:48
【问题描述】:
【问题讨论】:
标签:
jquery
html
jquery-mobile
mobile-website
【解决方案1】:
在这里找到答案
不知道如何将此问题标记为重复。
Programmatically selecting text in an input field on iOS devices (mobile Safari)
我的修复看起来像这样:-
<script type="text/javascript">
$('div,data-role=page').live('pageshow', function (event) {
jQuery.validator.unobtrusive.parse(".ui-page-active form");
$("input[type='text'], textarea, input[type='password'], input[type='number']").live('mouseup', function (e) { e.preventDefault(); });
$("input[type='text'], textarea, input[type='password'], input[type='number']").live('focus', function () {this.setSelectionRange(0, 9999); });
});
</script>
【解决方案2】:
您可以使用document.execCommand('selectAll');。但是,如果用户滚动页面,您将看到复制/粘贴菜单。
这是我用的:
function trySelect(el, evenInactive, select_ios) {
var select = function() {
try {
if (mojo.isTouch && select_ios && core.iosDevice && mojo.isInput(el) && document.execCommand) {
document.execCommand('selectAll');
} else {
el.select();
}
} catch (e) {
}
};
if (el && el.select && !el.disabled && (!el.readOnly || el.selectReadOnly) && mojo.isInput(el)) {
if (evenInactive || mojo.activeElement() === el) {
if (mojo.isTouch && core.webkitVer) { // http://code.google.com/p/chromium/issues/detail?id=32865
setTimeout(select, 0);
} else {
select();
}
}
}
}
这引用了一些内部函数:
- mojo.isTouch - 适用于触控设备
- core.iosDevice - 适用于 iOS 设备
- mojo.isInput - 测试输入元素
- mojo.activeElement() - document.activeElement
编辑:不应使用document.execCommand('selectAll');,而应使用el.setSelectionRange(0, el.value.length);。这在 iOS5 上似乎可以正常工作......它可能无法在 iOS4 上工作(我没有要测试的 iOS4 设备)。
【解决方案3】:
这个对我有用。
$("input[type='text'],select,textarea").focus(function () {
$(this).addClass('text-focus');
});
$("input[type='text'],select,textarea").blur(function () {
$(this).removeClass('text-focus');
});
.text-focus
{
border: 1px solid #ea9a00;
}
【解决方案4】:
不妨试试这个:
vmouseup
用于处理 touchend 或 mouseup 事件的标准化事件
JS:
$("#souper_fancy").focus(function() {
$(this).select();
});
$("#souper_fancy").vmouseup(function(e){
e.preventDefault();
});