Dre*_*TeK 6 html javascript jquery select ios
创建"任意"类型的跨浏览器文本框/输入字段,可以在单击/点击时选择其内容.
多年来一直困扰着许多问题.
问题:
使用触摸设备tap时,鼠标使用事件时会触发click事件.在Apple设备上,点击事件不会触发onclick或onfocus.这不是一个Safari的具体问题,因为谷歌Chrome浏览器对苹果设备,但同样的问题不是在Android设备上.苹果设备处理点击事件的方式明显不同.
选择文本的标准方法是简单地使用:
$('input').focus(function () {
$(this).select();
});
Run Code Online (Sandbox Code Playgroud)
堆栈溢出中提到的另一个选定的工作是:
$('input').focus(function () {
this.select(); //no jquery wrapper
}).mouseup(function (e) {
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
两者都运行良好,但都不适用于苹果设备.
我找到的唯一可行解决方案是根据这篇文章创建一个选择范围.这是纯粹的JavaScript,效果很好.
$('input').click(function () {
document.getElementById('ID').selectionStart = 0
document.getElementById('ID').selectionEnd = 999
});
Run Code Online (Sandbox Code Playgroud)
主解决方案
凭借这些知识,我想出了一个我自己的组合解决方案.
$('.Select').focus(function () {
this.select();
this.setSelectionRange(0, 9999);
}).mouseup(function (e) {
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
重新审视问题
这是一个长期存在的问题,我认为这个问题已经解决但现在我们已经到了2016年,问题就像行尸走肉一样从地球上升起.
该规范现在明确指出:
您不能在'HTMLInputElement'上使用'setSelectionRange':输入元素的类型('number')不支持选择.
因此,主代码将不再适用于Apple设备的数字字段.
重要的附加信息:我讨厌苹果.
$('.Select').focus(function () {
this.select();
this.setSelectionRange(0, 9999);
}).mouseup(function (e) {
e.preventDefault();
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input type text
<br/><input type="text" value="click me" class="Select">
<br/>Input type number
<br/><input type="number" value="0" class="Select">
<br/>I dont like apples.Run Code Online (Sandbox Code Playgroud)
那这个呢?
function addClickSelector(obj) {
function selectText(event) {
event.target.selectionStart = 0
event.target.selectionEnd = event.target.value.length
};
if (obj.addEventListener) {
obj.addEventListener("click", selectText, false);
} else {
obj.attachEvent("onclick", selectText);
}
};
[].forEach.call(document.getElementsByClassName('selectOnClick'), addClickSelector);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4322 次 |
| 最近记录: |